python sort list of tuple

后端 未结 3 683
温柔的废话
温柔的废话 2021-01-22 13:21

I am trying to sorting a list of tuple. for example, If

>>>recommendations = [(\'Gloria Pritchett\', 2), (\'Manny Delgado\', 1), (\'Cameron Tucker\',          


        
3条回答
  •  借酒劲吻你
    2021-01-22 13:53

    My variation on the sorted theme. I like using itemgetter:

    >>> 
    >>> from operator import itemgetter
    >>> name = itemgetter(0)
    >>> score = itemgetter(1)
    >>> recommendations = [('Gloria Pritchett', 2), ('Manny Delgado', 1), ('Cameron Tucker', 1), ('Luke Dunphy', 3)]
    >>> print '\n'.join(map(name, sorted(recommendations, key = score, reverse = True)))
    Luke Dunphy
    Gloria Pritchett
    Manny Delgado
    Cameron Tucker
    >>> 
    

提交回复
热议问题