简体   繁体   中英

Python - list in a list string reversing with sort

I am trying to sort lists in a list by an int, then by a string.

lst = [['Bob', 22], ['Jim', 33], ['Stan', 22]]
lst.sort(key = lambda x: (x[1], -x[0]), reverse = True)

As you can see, I am trying to sort them by their age and then by their names if they have the same age, in descending order. This, however, returns an error saying TypeError: bad operand type for unary -: 'str' , as I am using a negative sign to try and not reverse the String, so that it will remain being sorted in ascending order

How do I sort it in descending order by age, and then ascending order by name?

it should return:

[['Jim', 33], ['Bob', 22], ['Stan', 22]]

Sort straight-ahead (not reversed) and negate the age instead:

lst.sort(key=lambda x: (-x[1], x[0]))

This sorts on age in descending order (since -33 will sort before -22), then on name in alphabetical order.

Demo:

>>> lst = [['Stan', 22], ['Jim', 33], ['Bob', 22]]
>>> sorted(lst, key=lambda x: (-x[1], x[0]))
[['Jim', 33], ['Bob', 22], ['Stan', 22]]

I swapped Stan and Bob in my demo, as compared to your sample, to illustrate that the names really are sorted in alphabetical order and were not just left in relative order by Python's stable sort.

 >>> m=[['mahesh',1],['a',2]]
 >>> sorted(m)
 [['a', 2], ['mahesh', 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