2014-03-12 70 views
2

我想學習一些Python的功能方面。我期待編寫轉換一個理解:函數式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]} 

我能夠打造本作ac,但在兩個步驟:

schools_by_grade = {grade: [a] for grade in a['grades']} 
schools_by_grade.update({grade: [c] for grade in c['grades']}) 

有關如何做到這一點的任何想法?

+0

我會去與defaultdict –

+0

合併勢在必行辦法(循環)可以使用排序,GROUPBY和字典理解這樣做,但它不會是相當 –

回答

1

當務之急是更Python在這裏:

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) } 
+0

這是非常感謝您給我說, –

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']} 
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)