简体   繁体   English

如何根据元组中另一个值(第三个值)的降序对元组的排序列表(基于第二个值)中的相似值进行排序

[英]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.

相关问题 按元组的第二个和第三个值对三元素元组列表进行排序和计数 - Sort & count list of 3-element tuples by second and third value of a tuple 如何根据元组列表中的值对元组进行排序 - How to sort a tuple based on a value within the list of tuples 基于第二个值的元组列表中的第一个元组值 - First tuple value in tuples list based on second value 根据元组中的值拆分一个元组列表 - split a list of tuples based on the value in the tuple 根据元组内的值拆分元组列表 - Split list of tuples based on value within tuple 如何将列表中的元组分组,这些元组具有与一项相似的值,然后根据另一项对它们进行排序? - How can I group tuples inside a list that have a similar value of one item and then sort them based on another item? 根据索引 1 处的值按升序对元组列表进行排序 - Sort list of tuples in ascending order based on value at index 1 根据元组中的字典值删除元组列表中的元组 - Remove tuples within a list of tuples based on dictionary value within the tuple 如何在Python中按值降序对元组列表中的元素进行排序 - how can i sort elements in a list of tuples by value in descending order in Python Python 如何根据元组列表中的值对字典列表进行排序 - Python how to order a list of dictionaries based on a value in list of tuples
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM