简体   繁体   English

Python-按第二个元素然后按第三个元素对嵌套列表进行排序

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

相关问题 允许用户输入单词的列表位置以返回到列表中的第二和第三元素 - Allow the user to input the list position of the word to RETURN to 2nd and 3rd element from the list Python:如何删除文本文件每一行的第二和第三元素/变量 - Python: How to delete the 2nd and 3rd element/variable for every line of text file Selenium Webdriver,python-单击页面上的1st / 2nd / 3rd / etc元素? - Selenium Webdriver, python - click 1st/2nd/3rd/etc element on a page? 使用第一个元素的值获取结果集中第二个和第三个元素的值 - get values of 2nd and 3rd element of a result set using the value of the 1st element python。 根据第二个元素在嵌套列表中计算每个元素的第三个元素的最大值 - python. counting in nested list the max of 3rd element of each element according to the second element Append 列表的每个第二个元素(Python) - Append every 2nd element of list (Python) 在 Python 中查找列表的第二个元素的地址 - Find the address of the 2nd element of a list in Python Python 元组列表将第二个元素与唯一的第一个元素合并 - Python list of tuples merge 2nd element with unique first element 如何在 Python 的列表中找到第一个、第二个、第三个最高值 - How to find the 1st, 2nd, 3rd highest values in a list in Python 如何根据第二个或第三个单词或类似的东西在python中按字母顺序对句子列表进行排序 - How can I sort a list for sentence alphabetically in python based on 2nd or 3rd word or something like that
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM