根据第二个参数对元组进行排序 [英] Sort tuples based on second parameter
本文介绍了根据第二个参数对元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的元组列表:
I have a list of tuples that look something like this:
("Person 1",10)
("Person 2",8)
("Person 3",12)
("Person 4",20)
我要生成的是按元组的第二个值按升序排序的列表.因此,排序后L [0]应该为("Person 2", 8)
.
What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be ("Person 2", 8)
after sorting.
我该怎么做?使用Python 3.2.2如果有帮助.
How can I do this? Using Python 3.2.2 If that helps.
推荐答案
您可以将key
参数用于list.sort()
:
my_list.sort(key=lambda x: x[1])
或者更快一点
my_list.sort(key=operator.itemgetter(1))
(与任何模块一样,您需要import operator
才能使用它.)
(As with any module, you'll need to import operator
to be able to use it.)
这篇关于根据第二个参数对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文