简体   繁体   中英

Sort list of tuples by specific tuple element in Python 3

I have a list of tuples:

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')]

I want to sort them all by their last name's. If the last names of two student's are the same, then I'd like to search by the first name. How?

Thanks.

========================

So, I've got this so far:

tple_list.sort(key=operator.itemgetter(4), reverse=False)

This takes the list and sorts it by last name. I have people with the same last name though, so how do I sort by their first name if their last name is the same?

Use itemgetter from Python's operator module to sort using multiple indices in any order.

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)

output

[('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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM