我正在尝试学习 Python 的一些功能方面。我正在寻找可以转换的理解:
a = {'name': 'school a', 'grades': [3, 4, 5]}
b = {'name': 'school b', 'grades': [3, 4, 5]}
c = {'name': 'school c', 'grades': [6, 7, 8]}
到:
schools_by_grades = {3: [a, b], 4: [a, b], 5: [a, b], 6: [c], 7: [c], 8: [c]}
我能够为 a 和 c 创建这个,但是分两步:
schools_by_grade = {grade: [a] for grade in a['grades']}
schools_by_grade.update({grade: [c] for grade in c['grades']})
关于如何做到这一点有什么想法吗?
请您参考如下方法:
命令式在这里更像 Pythonic:
d = defaultdict(lambda: [])
for school in a, b, c:
for g in school['grades']:
d[g].append(school)
这是“函数式”方法,但正如预测的那样,它并不漂亮:
fst = lambda (x,_): x
grade_to_school = ((g,x) for x in a,b,c for g in x['grades'])
d = { g : list(y) for g,y in groupby(sorted(grade_to_school, key=fst), key=fst) }
