首页 > 代码库 > python之itemgetter函数:对字典列表进行多键排序
python之itemgetter函数:对字典列表进行多键排序
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}
python之itemgetter函数:对字典列表进行多键排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。