myDict = {}
myLog = [['a', 917], ['b', 312], ['c', 303],['d', 212], ['a', 215],
['b', 212], ['c', 213], ['d', 202]]
# For each of the log in your input log
for log in myLog:
# If it is already exist, you append it
if log[0] in myDict:
myDict[log[0]].append(log[1])
# Otherwise you can create a new one
else:
myDict[log[0]] = [log[1]]
# Simple test to show it works
while True:
lookup = input('Enter your key: ')
if lookup in myDict:
print(myDict[lookup])
else:
print('Item not found.')
斯文·马纳奇的答案更聪明更好,但这就是我提出的版本。我能看出我的解决办法的局限性。你知道吗
这是一个标准问题集合.defaultdict解决:
遍历列表,并将每个值附加到正确的键:
我将
dict
重命名为my_dict
,以避免隐藏内置类型。你知道吗相关问题 更多 >
编程相关推荐