如何按一个值对另一个元组列表排序,然后对另一个值进行排序?

编程入门 行业动态 更新时间:2024-10-09 20:27:02
本文介绍了如何按一个值对另一个元组列表排序,然后对另一个值进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我会讲到这一点,

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.

更多推荐

如何按一个值对另一个元组列表排序,然后对另一个值进行排序?

本文发布于:2023-10-12 16:22:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!