简体   繁体   中英

Multilevel sort on list of tuples but with change in sort order

I need to sort the below list:

list1 = [('a', 1, 2), ('b', 1, 3), ('c', 2, 1)]

based on 2nd(asc) & 3rd element(desc) of each tuple resulting in:

 [('b',1,3),('a',1,2),('c',2,1)]

I tried using

 sorted(list1, key=lambda x: x[1], x[2], reverse=lambda x:(True,False)  #TypeError: an integer is required (got type function)

 sorted(list1, key=lambda x: x[1], x[2], reverse=(True,False))  #TypeError: an integer is required (got type function)

 sorted(list1, key=lambda x: x[1], x[2], reverse=True,False)   #SyntaxError: positional argument follows keyword argument

How to sort one key in ascending order & other in descending order?

First, you should provide one value as key. In this case, you can use tuple of the numbers.

The last value should be negative as you want it to be sorted in reverse order since a > b imply -a < -b

>>> sorted(list1, key=lambda x: (x[1],-x[2]) )
[('b',1,3),('a',1,2),('c',2,1)]

In the key parameter, reverse the 2nd element should do the trick. For instance,

list1 = [('a', 1, 2), ('b', 1, 3), ('c', 2, 1)]
print(sorted(list1, key=lambda x: (x[1], -x[2])))

Will outputs

>>> print(sorted(list1, key=lambda x: (x[1], -x[2])))
[('b', 1, 3), ('a', 1, 2), ('c', 2, 1)]

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