按第二项(整数值)对元组列表进行排序 [英] Sort a list of tuples by 2nd item (integer value)

查看:27
本文介绍了按第二项(整数值)对元组列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的元组列表:

I have a list of tuples that looks something like this:

[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

我想按元组内的整数值按升序对这个列表进行排序.可能吗?

I want to sort this list in ascending order by the integer value inside the tuples. Is it possible?

推荐答案

尝试在 sorted() 中使用 key 关键字.

Try using the key keyword with sorted().

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])

key 应该是一个函数,用于标识如何从您的数据结构中检索可比较的元素.在您的情况下,它是元组的第二个元素,因此我们访问 [1].

key should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1].

对于优化,请参阅 jamylak 使用 itemgetter(1) 的响应,它本质上是 lambda x: x[1] 的更快版本.

For optimization, see jamylak's response using itemgetter(1), which is essentially a faster version of lambda x: x[1].

这篇关于按第二项(整数值)对元组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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