问题
I'll get to the point,i have this:
ocurrencias = [('quiero', 1), ('aprender', 1), ('a', 1), ('programar', 1), ('en', 1), ('invierno', 2), ('hace', 1), ('frio', 1), ('este', 1)]
I want to sort it by the second value of the tuples and then by their string value and then print every element to get this:
output:invierno 2
a 1
aprender 1
en 1
este 1
frio 1
hace 1
programar 1
quiero 1
Don't know if i'm making it clear enough,but i'm not really proficient at english so forgive me.
Thanks in advance
回答1:
Use sorted
with a key which makes a reversed version of each tuple, to sort the second value in descending order, you can add a -
in front to negate the value:
sorted(ocurrencias, key = lambda x: (-x[1], x[0]))
# [('invierno', 2), ('a', 1), ('aprender', 1), ('en', 1), ('este', 1), ('frio', 1), ('hace', 1), ('programar', 1), ('quiero', 1)]
As commented by @Jonathon, the reason this works is due to the fact that lists and tuples comparison happens in order i.e, compare the first element; if not equal then the second element, to see more about object comparison in python.
来源:https://stackoverflow.com/questions/41603482/how-can-i-sort-a-list-of-tuples-by-one-of-its-values-and-then-the-other