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)
通常有一个符合您需求的内置程序,例如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)
希望这可以帮助.