我在 Python 中有以下列表:
students = ["Anderson", "Peter", "Anderson", "Bastian"]
courses = ["Biology", "History", "Maths", "History"]
我编写了一个 for 循环,试图在字典中关联这些对,以便:
Anderson-Biology
Peter-History
Anderson-Maths
Bastian-History
for循环如下:
test_dict = {}
for i in range (0, len(students)):
test_dict[students[i]] = courses[i]
但是,当打印字典时,我得到:
{'Bastian': 'History', 'Anderson': 'Maths', 'Peter': 'History'}
“安德森”发生了什么:“生物学,我有办法解决这个问题吗?”
请您参考如下方法:
Python 词典不接受重复键,在您的代码中它只保留最后一个 'Anderson'。
相反,您可以使用 dict.setdefault 方法将重复的值放入列表中:
>>> d={}
>>> for i,j in zip(students,courses):
... d.setdefault(i,[]).append(j)
...
>>> d
{'Peter': ['History'], 'Anderson': ['Biology', 'Maths'], 'Bastian': ['History']}
>>>
