Reputation: 10173
First, I have noticed that there are many questions posted on sorting lists of tuples, however after looking over a few posts I did not see any of the questions with this particular format for the list. Apologies in advance then for a potential repeat question, however I think this should be simple.
Let the list of tuples be this:
my_list = [(('G', 'J', 'I'), 1.0), (('E', 'H', 'F'), 1.0), (('F', 'H', 'G'), 0.8889), (('I', 'K', 'J'), 0.8889), (('H', 'I', 'G'), 0.8889), (('H', 'J', 'I'), 0.875)]
Note that each tuple in the list consists of 1: another tuple of length 3 with 3 letters, and 2: a floating point number. My sorting objective is simple then: 1st sort the list of tuples by the floating point number, 2nd break any ties in the floating point number by then sorting by the first letter in the length-3 tuple, 3rd break any ties in that letter by sorting by the 2nd letter in the length-3 tuple. Desired output would then be:
sorted_list = [(('E', 'H', 'F'), 1.0), (('G', 'J', 'I'), 1.0), (('F', 'H', 'G'), 0.8889), (('H', 'I', 'G'), 0.8889), (('I', 'K', 'J'), 0.8889), (('H', 'J', 'I'), 0.875)]
in this particular example, sorting on the 2nd letter to break ties on the first letter did not appear, although it does in my larger dataset.
Thanks!
Upvotes: 1
Views: 2543
Reputation: 78556
Here's one way to do it: the first sort is done in reverse on the float, while the ties are broken by sorting on the inner tuple:
srt_lst = sorted(my_list, key=lambda (x, y): (-y, x)) #python 2
print(srt_lst)
# [(('E', 'H', 'F'), 1.0), (('G', 'J', 'I'), 1.0), (('F', 'H', 'G'), 0.8889), (('H', 'I', 'G'), 0.8889), (('I', 'K', 'J'), 0.8889), (('H', 'J', 'I'), 0.875)]
In Python 3, you'll have to index the lambda's single parameter to access the items and use them for sorting:
srt_lst = sorted(my_list, key=lambda tup: (-tup[1], tup[0]))
Upvotes: 5