[英]Sort list of tuples by specific tuple element in Python 3
我有一个元组列表:
tple_list = [('4', '4', '1', 'Bart', 'Simpson'),
('1', '2', '6', 'Lisa', 'Simpson'),
('6', '3', '4', 'Homer', 'Simpson'),
('2', '3', '1', 'Hermione', 'Nobody'),
('1', '2', '3', 'Bristol', 'Palace')]
我想按姓氏对它们进行排序。 如果两个学生的姓氏相同,那么我想按名字搜索。 怎么样?
谢谢。
========================
因此,到目前为止,我已经做到了:
tple_list.sort(key=operator.itemgetter(4), reverse=False)
这将获取列表并按姓氏对其进行排序。 虽然我的姓氏相同,但是如果姓氏相同,该如何按姓氏排序?
使用Python 运算符模块中的 itemgetter
可以按任意顺序使用多个索引进行排序。
from operator import itemgetter
tple_list = [('4', '4', '1', 'Bart', 'Simpson'),
('1', '2', '6', 'Lisa', 'Simpson'),
('6', '3', '4', 'Homer', 'Simpson'),
('2', '3', '1', 'Hermione', 'Nobody'),
('1', '2', '3', 'Bristol', 'Palace')]
tple_list.sort(key=itemgetter(4, 3)) # lastname, firstname
print(tple_list)
输出
[('2', '3', '1', 'Hermione', 'Nobody'),
('1', '2', '3', 'Bristol', 'Palace'),
('4', '4', '1', 'Bart', 'Simpson'),
('6', '3', '4', 'Homer', 'Simpson'),
('1', '2', '6', 'Lisa', 'Simpson')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.