我有一个列表 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/