问题
I have a list of tuples of the format
[("d",21,5),(e,21,4),("a",20,1),("b",20,3),("c",20,2),...]
where the first values (a,b,c etc) are unique and the other two values in tuple might repeat.(like 20)
I want to sort the list based on 2nd element(here 20,21) in tuple in ascending order, like
[a,b,c,d,e]
Then i want the values sorted based on same numbers like (a,b,c) where sorted based on 20 and (d,e) based on 21 to be sorted based on 3rd value(here 1,2,3,4,5) of tuple in descending order, like
[b,c,a,d,e]
回答1:
If your original list looks like this:
L = [("d",21,5),(e,21,4),("a",20,1),("b",20,3),("c",20,2),...]
Then, you can sort it the way you want, by defining a 2-tuple key in the sort function:
L.sort(key=lambda t: (t[1],-t[2]))
This ensures that the list is sorted by the second element in the tuple, while ties are broken by the negated value of the third element in the tuple (i.e. in descending order by the third element)
来源:https://stackoverflow.com/questions/29551840/how-to-sort-similar-values-in-a-sorted-list-based-on-second-value-of-tuples-ba