对包含元组的元组进行排序

Huu*_*uze 12 python sorting tuples

我有以下元组,其中包含元组:

MY_TUPLE = (
    ('A','Apple'),
    ('C','Carrot'),
    ('B','Banana'),
)
Run Code Online (Sandbox Code Playgroud)

我想根据内部元组中包含的第二个值来排序这个元组(即,排序Apple,Carrot,Banana而不是A,B,C).

有什么想法吗?

Mar*_*rot 22

from operator import itemgetter

MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
Run Code Online (Sandbox Code Playgroud)

或没有itemgetter:

MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是:如果您要排序的值可能有重复,则可以通过向[`itemgetter`](http://docs.python.org/library/operator.html#operator)提供其他参数来回退到另一个值. itemgetter),例如`itemgetter(1,0)`. (2认同)

mwi*_*ams 7

排序迷你如何

通常有一个符合您需求的内置程序,例如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)]
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.