## 字典列表排序
1 students = [ 2 {"name": "Stanley", "age": 22, "score": 92}, 3 {"name": "Peter", "age": 19, "score": 99}, 4 {"name": "Well", "age": 23, "score": 82}, 5 {"name": "Bob", "age": 20, "score": 88}, 6 {"name": "Lily", "age": 22, "score": 95} 7 ] 8 students_by_age = sorted(students, key=lambda s: s["age"]) 9 print(students_by_age) 10 """ 11 [{'name': 'Peter', 'age': 19, 'score': 99}, 12 {'name': 'Bob', 'age': 20, 'score': 88}, 13 {'name': 'Stanley', 'age': 22, 'score': 92}, 14 {'name': 'Lily', 'age': 22, 'score': 95}, 15 {'name': 'Well', 'age': 23, 'score': 82}] 16 """ 17 18 # 使用operator.itemgetter 进行排序,代替sorted函数中的key的匿名函数 19 # 排序速度比匿名函数更快,也支持多个关键字同时排序,同样适用与min(),max()等函数中的key关键字 20 21 from operator import itemgetter 22 23 students_by_score_age = sorted(students, key=itemgetter("score", "age"), reverse=True) 24 print(students_by_score_age) 25 """ 26 [{'name': 'Peter', 'age': 19, 'score': 99}, 27 {'name': 'Lily', 'age': 22, 'score': 95}, 28 {'name': 'Stanley', 'age': 22, 'score': 92}, 29 {'name': 'Bob', 'age': 20, 'score': 88}, 30 {'name': 'Well', 'age': 23, 'score': 82}] 31 """
参考资料:
Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).