When I sort my list of tuples by descending with numerical values with this function :
data.sort(key=lambda tup: tup[1], reverse=True)
I have this order of tuples in my list :
data = [("a", 8001),
("b", 8000),
("c", 8),
("d", 10)]
It's sorted by alphabet and not numerical. 8 > 10 because 8 is greater than first letter of 10 which is 1.
How can I sort my list of tuples by numerical descending order ?
CodePudding user response:
The original code works just fine
>>> data = [("a", 8001),
... ("b", 8000),
... ("c", 8),
... ("d", 10)]
>>>
>>> data
[('a', 8001), ('b', 8000), ('c', 8), ('d', 10)]
>>> data.sort(key=lambda tup: tup[1], reverse=True)
>>>
>>> data
[('a', 8001), ('b', 8000), ('d', 10), ('c', 8)]
CodePudding user response:
Try:
sorted(data, key=lambda x: -int(x[1]))
Output:
[('a', '8001'), ('b', '8000'), ('d', '10'), ('c', '8')]
Actually your initial code looks fine, you only need to convert to int
like:
data.sort(key=lambda tup: int(tup[1]), reverse=True)