Sorting a tuple that contains tuples

前端 未结 4 850
星月不相逢
星月不相逢 2020-11-30 03:28

I have the following tuple, which contains tuples:

MY_TUPLE = (
    (\'A\',\'Apple\'),
    (\'C\',\'Carrot\'),
    (\'B\',\'Banana\'),
)

I\

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 04:14

    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():

    >>> 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.

提交回复
热议问题