python之itemgetter函数:对字典列表进行多键排序

时间:2021-07-18 20:45:13

itemgetter函数:对字典列表进行多键排序

 1 from operator import itemgetter
2
3 list_people = [
4 {'name': 'Mike', 'age': 22, 'score': 90},
5 {'name': 'Alice', 'age': 22, 'score': 90},
6 {'name': 'Lee', 'age': 26, 'score': 92},
7 {'name': 'Ben', 'age': 26, 'score': 85},
8 {'name': 'Tom', 'age': 33, 'score': 90},
9 {'name': 'Jill', 'age': 41, 'score': 72}
10 ]
11
12 print('根据名字排序:')
13 for i in sorted(list_people, key=lambda person: person['name']):
14 '''sorted()函数默认升序排列'''
15 print(i)
16
17 print('\n根据得分降序排列:')
18 for i in sorted(list_people, key=itemgetter('score'), reverse=True):
19 '''参数reverse=True表示降序排列'''
20 print(i)
21
22 print('\n根据名字和年龄多键排序:')
23 for i in sorted(list_people, key=itemgetter('name', 'age')):
24 print(i)

运行结果:

1 根据名字和年龄多键排序:
2 {'name': 'Alice', 'age': 22, 'score': 90}
3 {'name': 'Ben', 'age': 26, 'score': 85}
4 {'name': 'Jill', 'age': 41, 'score': 72}
5 {'name': 'Lee', 'age': 26, 'score': 92}
6 {'name': 'Mike', 'age': 22, 'score': 90}
7 {'name': 'Tom', 'age': 33, 'score': 90}