python - 从 python 列表中获取字典

标签 python list python-2.7 dictionary

我有一个列表 my_list = ['a', 'b', 'c', 'd'] 我需要创建一个字典,看起来像

{ 'a': ['a', 'b', 'c', 'd'], 
  'b': ['b', 'a', 'c', 'd'], 
  'c': ['c', 'a', 'b', 'd'], 
  'd': ['d', 'a', 'b', 'c'] }

每个元素作为其值是列表,但第一个元素是它本身。

这是我的代码

my_list = ['1', '2', '3', '4']
my_dict=dict()

for x in my_list:        
    n = my_lst[:]
    n.remove(x)
    n= [x] + n[:]
    my_dict[x] = n

print my_dict

给出

{'1': ['1', '2', '3', '4'], 
 '3': ['3', '1', '2', '4'], 
 '2': ['2', '1', '3', '4'], 
 '4': ['4', '1', '2', '3']}

根据需要。 但我认为这不是最好的方法。任何优化帮助将不胜感激。

最佳答案

>>> seq
    ['a', 'b', 'c', 'd']

>>> {e: [e]+[i for i in seq if i != e] for e in seq}
    {'a': ['a', 'b', 'c', 'd'],
     'b': ['b', 'a', 'c', 'd'],
     'c': ['c', 'a', 'b', 'd'],
     'd': ['d', 'a', 'b', 'c']}

关于python - 从 python 列表中获取字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092558/

相关文章:

python - 调用列表内的元组

python - 如何在 Python 函数中返回左值?

python - Elasticsearch 在 python 中更新文档

python - 新手 Python 脚本 - read()

python - 如何 conda 打包基础环境

list - R:将列表项转换为对象

c# - 在 C# 中将 DataTable 转换为 List<T>

Python json获取具体故事和图片

python-2.7 - Python子进程: Know when a command has finished

python - 根据python中列表的值以不同的间隔拼接列表