按第二项对元组列表进行排序(整数值) [英] Sort a list of tuples by 2nd item (integer value)
本文介绍了按第二项对元组列表进行排序(整数值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的元组列表:
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?
推荐答案
尝试将key
关键字与sorted()
一起使用.
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]
.
为进行优化,请参阅使用itemgetter(1)
的jamylak响应,该响应本质上是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屋!
查看全文