在Python3中,按特定元组元素对元组列表进行排序

2024-06-16 13:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表:

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)

这将获取列表并按姓氏排序。不过,我也有姓相同的人,如果他们的姓相同,我怎么按他们的名字排序呢?你知道吗


Tags: 列表排序名字学生list元组lisabart
1条回答
网友
1楼 · 发布于 2024-06-16 13:15:57

使用Python的operator module中的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')]

相关问题 更多 >