operator.itemgetter() 字典列表排序

时间:2023-03-08 18:31:46

## 字典列表排序

 students = [
{"name": "Stanley", "age": 22, "score": 92},
{"name": "Peter", "age": 19, "score": 99},
{"name": "Well", "age": 23, "score": 82},
{"name": "Bob", "age": 20, "score": 88},
{"name": "Lily", "age": 22, "score": 95}
]
students_by_age = sorted(students, key=lambda s: s["age"])
print(students_by_age)
"""
[{'name': 'Peter', 'age': 19, 'score': 99},
{'name': 'Bob', 'age': 20, 'score': 88},
{'name': 'Stanley', 'age': 22, 'score': 92},
{'name': 'Lily', 'age': 22, 'score': 95},
{'name': 'Well', 'age': 23, 'score': 82}]
""" # 使用operator.itemgetter 进行排序,代替sorted函数中的key的匿名函数
# 排序速度比匿名函数更快,也支持多个关键字同时排序,同样适用与min(),max()等函数中的key关键字 from operator import itemgetter students_by_score_age = sorted(students, key=itemgetter("score", "age"), reverse=True)
print(students_by_score_age)
"""
[{'name': 'Peter', 'age': 19, 'score': 99},
{'name': 'Lily', 'age': 22, 'score': 95},
{'name': 'Stanley', 'age': 22, 'score': 92},
{'name': 'Bob', 'age': 20, 'score': 88},
{'name': 'Well', 'age': 23, 'score': 82}]
"""

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).