I have a list with three elements in the following format:
[('ABC', 'DEF', 2), ('GHI', 'JKL', 6), ('MNO', 'PQR', 22), ('ABC', 'STU', 2)...]
I would like to sort by last element numerically. Then by first element alphabetically. Lastly by the second element if there is a tie. So my output would be:
[('MNO', 'PQR', 22), ('GHI', 'JKL', 6), ('ABC', 'DEF', 2), ('ABC', 'STU', 2)...]
I've tried
list_name.sort(reverse=True, key=lambda x: x[2])
This only sorts by the last elements descending. How do I add the implement sorting the first and second element in that order alphabetically.
解决方案
Return a tuple, and negate the number instead of using reverse:
list_name.sort(key=lambda x: (-x[2],) + x[:2])
This returns (-item3, item1, item2) and sorting takes place first by the integer item3 in descending order, when tied on the number sorting is done on item1 (alphabetically, ascending order), then on item2.
In effect, tuples are sorted in lexicographical order.
Demo:
>>> list_name = [('ABC', 'DEF', 2), ('GHI', 'JKL', 6), ('MNO', 'PQR', 22), ('ABC', 'STU', 2)]
>>> list_name.sort(key=lambda x: (-x[2],) + x[:2])
>>> list_name
[('MNO', 'PQR', 22), ('GHI', 'JKL', 6), ('ABC', 'DEF', 2), ('ABC', 'STU', 2)]