如何基于元组中的另一个值(第三个值)以降序对元组的排序列表(基于第二个值)中的相似值进行排序 [英] 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

查看:174
本文介绍了如何基于元组中的另一个值(第三个值)以降序对元组的排序列表(基于第二个值)中的相似值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式的元组列表

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),...]

其中第一个值(a,b,c等)是唯一的,而元组中的其他两个值可能会重复.(例如20)

where the first values (a,b,c etc) are unique and the other two values in tuple might repeat.(like 20)

我想基于第二个元素(此处为20,21)以元组的升序对列表进行排序,例如

I want to sort the list based on 2nd element(here 20,21) in tuple in ascending order, like

[a,b,c,d,e]

[a,b,c,d,e]

然后我希望基于(a,b,c)相同的值对值进行排序,其中基于20的值进行排序,基于(21)的(d,e)的值基于第三值(此处为1,2,3, 4,5)元组按降序排列,例如

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]

[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),...]

然后,您可以通过在sort函数中定义一个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)

这篇关于如何基于元组中的另一个值(第三个值)以降序对元组的排序列表(基于第二个值)中的相似值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆