[英]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
I have a list of tuples of the format 我有一个格式的元组列表
[("d",21,5),(e,21,4),("a",20,1),("b",20,3),("c",20,2),...] [(“ 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) 其中第一个值(a,b,c等)是唯一的,而元组中的其他两个值可能会重复。(例如20)
I want to sort the list based on 2nd element(here 20,21) in tuple in ascending order, like 我想基于第二个元素(此处为20,21)在元组中按升序对列表进行排序,例如
[a,b,c,d,e] [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 然后我想基于相同的数字排序的值,例如(a,b,c),其中基于20排序的值,以及(d,e)基于21的排序值,要基于第三值排序(此处1,2,3,4,5 )的元组降序排列,例如
[b,c,a,d,e] [b,c,a,d,e]
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: 然后,您可以通过在sort函数中定义一个2元组键来对其进行排序:
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 (ie in descending order by the third element) 这样可以确保列表按元组中的第二个元素排序,而关系按元组中的第三个元素的取反值(即,按降序由第三个元素)断开
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.