groupby()函數同時返回分組關鍵字和一個與關鍵字相對應的可迭代對象,也可以使用defaultdict()創建一個一對多字典方便進行隨機訪問 ...
## itertools.groupby()分組字典列表數據
1 from operator import itemgetter 2 from itertools import groupby 3 4 5 students = [ 6 {'name': 'Peter', 'age': 19, 'score': 95}, 7 {'name': 'Lily', 'age': 22, 'score': 90}, 8 {'name': 'Stanley', 'age': 22, 'score': 92}, 9 {'name': 'Bob', 'age': 20, 'score': 88}, 10 {'name': 'Well', 'age': 20, 'score': 82} 11 ] 12 13 for key, group in groupby(sorted(students, key=itemgetter("age")), key=itemgetter("age")): 14 # groupby()函數同時返回分組關鍵字和一個與關鍵字相對應的可迭代對象 15 # itemgetter()同樣可以接收多個關鍵字,也可以使用匿名函數代替此函數,但速度相比之下較慢 16 print("Age: %s" % key) 17 for g in group: 18 print(g) 19 """ 20 Age: 19 21 {'name': 'Peter', 'age': 19, 'score': 95} 22 Age: 20 23 {'name': 'Bob', 'age': 20, 'score': 88} 24 {'name': 'Well', 'age': 20, 'score': 82} 25 Age: 22 26 {'name': 'Lily', 'age': 22, 'score': 90} 27 {'name': 'Stanley', 'age': 22, 'score': 92} 28 29 """ 30 # 也可以使用defaultdict()創建一個一對多字典方便進行隨機訪問 31 from collections import defaultdict 32 33 34 students_by_age = defaultdict(list) 35 for key, group in groupby(sorted(students, key=itemgetter("age")), key=itemgetter("age")): 36 for i in group: 37 students_by_age[key].append(i) 38 39 print(list(students_by_age[22])) 40 # [{'name': 'Lily', 'age': 22, 'score': 90}, {'name': 'Stanley', 'age': 22, 'score': 92}]
參考資料:
Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).