按第二项对元组列表进行排序(整数值)[重复]

本文翻译自:Sort a list of tuples by 2nd item (integer value) [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed last year . 去年关闭。

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? 可能吗?


#1楼

参考:https://stackoom.com/question/isIF/按第二项对元组列表进行排序-整数值-重复


#2楼

>>> from operator import itemgetter
>>> data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
>>> sorted(data,key=itemgetter(1))
[('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]

IMO using itemgetter is more readable in this case than the solution by @cheeken. IMO使用itemgetter是在这种情况下比@cheeken溶液更具有可读性。 It is also faster since almost all of the computation will be done on the c side (no pun intended) rather than through the use of lambda . 它也更快,因为几乎所有计算都将在c端完成(没有双关语),而不是通过使用lambda

>python -m timeit -s "from operator import itemgetter; data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=itemgetter(1))"
1000000 loops, best of 3: 1.22 usec per loop

>python -m timeit -s "data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=lambda x: x[1])"
1000000 loops, best of 3: 1.4 usec per loop

#3楼

Try using the key keyword with sorted() . 尝试将key关键字与sorted()

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

key should be a function that identifies how to retrieve the comparable element from your data structure. key应该是一个标识如何从数据结构中检索可比较元素的函数。 In your case, it is the second element of the tuple, so we access [1] . 在您的情况下,它是元组的第二个元素,因此我们访问[1]

For optimization, see jamylak's response using itemgetter(1) , which is essentially a faster version of lambda x: x[1] . 为了进行优化,请参阅使用itemgetter(1)进行的jamylak响应,该响应本质上是lambda x: x[1]的更快版本。


#4楼

From python wiki: 从python Wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

#5楼

As a python neophyte, I just wanted to mention that if the data did actually look like this: 作为一个Python新手,我只想提及一下,如果数据确实看起来像这样:

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

then sorted() would automatically sort by the second element in the tuple, as the first elements are all identical. 然后sorted()将自动按元组中的第二个元素进行排序,因为第一个元素都相同。


#6楼

添加到Cheeken的答案中,这是您按照第二项以降序对元组列表进行排序的方式。

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值