How to sort similar values in a sorted list (based on second value) of tuples based on another value(third value) in the tuple in descending order

隐身守侯 提交于 2019-12-08 09:03:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!