[英]Python - Sorting nested list by 2nd element, then by 3rd element
So i am sorting a list of nested lists of integers by firstly the 2nd element (in ascending order), which I have done using the following code: 因此,我首先通过第二个元素(按升序)对整数嵌套列表的列表进行排序,这是我使用以下代码完成的:
my_list.sort(key=lambda x: x[2])
Now, if there are repeats in the second element, I would like to then sort the list by the 3rd element (in descending order). 现在,如果第二个元素中有重复项,那么我想按第三个元素(以降序)对列表进行排序。 How would I go about this? 我将如何处理?
You can use a key function that returns a tuple instead. 您可以使用返回一个元组的键函数。 Negate the numeric value of an item if you want it to be sorted in the opposite direction. 如果希望以相反的方向对项目的数值进行求反,则取反。
my_list.sort(key=lambda x: (x[2], -x[3]))
Note that the index of 2 actually refers to the third item, and the index of 3 refers to the fourth item, but I assume that the index of 2 in the code you posted is the item you want to sort first. 请注意,索引2实际上是指第三项,索引3是第四项,但是我假设您发布的代码中的索引2是要首先排序的项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.