如何按一个值对另一个元组列表排序,然后对另一个值进行排序?
我会讲到这一点,
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.
预先感谢
使用sorted
和一个使每个元组具有相反版本的键,以降序对第二个值进行排序,您可以在-
中添加-
否定值的前面:
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)]
正如@Jonathon所评论的那样,之所以起作用,是因为列表和元组比较是按顺序进行的,即比较第一个元素;如果不相等,则使用第二个元素,以了解有关python中对象比较的更多信息.
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.