我试图学习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']})
关于如何做到这一点的任何想法?
答案 0 :(得分:1)
势在必行的是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) }
答案 1 :(得分:0)
你可以这样做:
schools_by_grades = {i: [school['name'] for school in (a, b, c)
if i in school['grades']]
for i in range(20) if any(i in school['grades']
for school in (a, b, c))}
但你可能不应该。
这给了我:
{3: ['school a', 'school b'],
4: ['school a', 'school b'],
5: ['school a', 'school b'],
6: ['school c'],
7: ['school c'],
8: ['school c']}
答案 2 :(得分:0)
如果具体如此,我建议为该操作制作一个功能。
def AddSchoolsByGrades(schools_by_grades, school_dict):
# if there is a space in the name, it will take the last word of the name
name = school_dict["name"].split(" ")[-1]
for g in school_dict["grades"]:
# if there is no entry for the grade, then make one
if not g in schools_by_grades.keys():
schools_by_grades[g] = []
# add the name of the school to the grade
schools_by_grades[g].append(name)
# simple trick to remove any duplicates
schools_by_grades[g] = list(set(schools_by_grades[g]))
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 = {}
AddSchoolsByGrades(schools_by_grades, a)
AddSchoolsByGrades(schools_by_grades, b)
AddSchoolsByGrades(schools_by_grades, c)