我想创建词典,使用度作为键,值必须是所有取得该度数的学生。下面,sam采取bcom,jack采取bcom等等。提前谢谢
students = ['sam','jack','rose','khan','marry','xio']
degrees = ['bcom','bcom','bsc','arts','bsc','arts']
答案 0 :(得分:2)
可能是这个代码片段做你想做的事情:
dictionary = {}
for degree, student in zip(degrees, students):
dictionary.setdefault(degree, []).append(student)
<'>''arts':['khan','xio'],'bcom':['sam','jack'],'bsc':['rose','marry']}
答案 1 :(得分:1)
这是实现此行为的另一种紧凑方式:
s2d = dict(zip(students, degrees))
{k: [s for s, d in s2d.items() if d==k] for k in degrees}
{'bcom':['sam','jack'],'bsc':['rose','marry'],'arts':['khan','xio']}
虽然如果你有相同的学生将采取两个不同的学位
,它将无效