我有字典和清单:
results = {"Alice":[], "Bob":[], "Clare":[], "Dennis":[], "Eva":[]}
list_of_names = ['Bob', 'Alice', 'Clare', 'Eva', 'Dennis']
,我想相应地用index + 1值填充这些列表。 这样,如果我们在字典上方有列表,将像这样
results = {"Alice":[2], "Bob":[1], "Clare":[3], "Dennis":[5], "Eva":[4]}
这是我当前的代码
Aindex = list_of_names.index("Alice")
Bindex = list_of_names.index("Bob")
Cindex = list_of_names.index("Clare")
Dindex = list_of_names.index("Dennis")
Eindex = list_of_names.index("Eva")
Aindex = Aindex + 1
Bindex = Bindex + 1
Cindex = Cindex + 1
Dindex = Dindex + 1
Eindex = Eindex + 1
results["Alice"].append(Aindex)
results["Bob"].append(Bindex)
results["Clare"].append(Cindex)
results["Dennis"].append(Dindex)
results["Eva"].append(Eindex)
有什么方法可以缩短这段代码,使其适用于任何数量的字典/列表条目?
答案 0 :(得分:3)
是的。一行包含字典理解,enumerate
从1开始:
list_of_names = ['Bob', 'Alice', 'Clare', 'Eva', 'Dennis']
results = {name:[i] for i,name in enumerate(list_of_names,1)}
>>> results
{'Alice': [2], 'Bob': [1], 'Clare': [3], 'Dennis': [5], 'Eva': [4]}
答案 1 :(得分:0)
如果要使用字典中的现有列表
results = {"Alice":[], "Bob":[], "Clare":[], "Dennis":[], "Eva":[]}
list_of_names = ['Bob', 'Alice', 'Clare', 'Eva', 'Dennis']
for i,j in enumerate(list_of_names,1):
results[j].append(i)