python 对包含元组的元组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/222752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting a tuple that contains tuples
提问by Huuuze
I have the following tuple, which contains tuples:
我有以下元组,其中包含元组:
MY_TUPLE = (
('A','Apple'),
('C','Carrot'),
('B','Banana'),
)
I'd like to sort this tuple based upon the secondvalue contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).
我想根据内部元组中包含的第二个值对这个元组进行排序(即,排序 Apple、Carrot、Banana 而不是 A、B、C)。
Any thoughts?
有什么想法吗?
回答by Markus Jarderot
from operator import itemgetter
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
or without itemgetter
:
或没有itemgetter
:
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
回答by mwilliams
From Sorting Mini-HOW TO
Often there's a built-in that will match your needs, such as str.lower(). The operator module contains a number of functions useful for this purpose. For example, you can sort tuples based on their second element using operator.itemgetter():
通常有一个内置函数可以满足您的需求,例如 str.lower()。操作员模块包含许多用于此目的的函数。例如,您可以使用 operator.itemgetter() 根据元组的第二个元素对元组进行排序:
>>> import operator
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Hope this helps.
希望这可以帮助。
回答by Eli Courtwright
sorted(my_tuple, key=lambda tup: tup[1])
In other words, when comparing two elements of the tuple you're sorting, sort based on the return value of the function passed as the key parameter.
换句话说,当比较要排序的元组的两个元素时,根据作为关键参数传递的函数的返回值进行排序。
回答by Huuuze
I achieved the same thing using this code, but your suggestion is great. Thanks!
我使用此代码实现了相同的目的,但是您的建议很棒。谢谢!
templist = [ (line[1], line) for line in MY_TUPLE ]
templist.sort()
SORTED_MY_TUPLE = [ line[1] for line in templist ]