如何按一个值对另一个元组列表排序,然后对另一个值进行排序? [英] How can i sort a list of tuples by one of it's values and then the other?

查看:96
本文介绍了如何按一个值对另一个元组列表排序,然后对另一个值进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会讲到这一点,

    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.

这篇关于如何按一个值对另一个元组列表排序,然后对另一个值进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆