简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM