python sort list of tuple

后端 未结 3 686
温柔的废话
温柔的废话 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:36

    You can pass in the key to sorted:

    >>> s = sorted(recommendations, key=lambda x: x[1], reverse=True)
    [('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Manny Delgado', 1), ('Cameron Tucker', 1)]
    

    Then get the names:

    names = [x[0] for x in s]
    # ['Luke Dunphy', 'Gloria Pritchett', 'Manny Delgado', 'Cameron Tucker']
    

    If you've noticed, Manny Delgado and Cameron Tucker are tied based on their key(1), but Manny Delgado comes before Cameron Tucker, because python sorting is in-place. However, based on your desired output, you want the ties in primary key to be resolved using the secondary key (the name in this case). You can do this by first sorting by name and then sorting by the primary integer key:

    t = sorted(recommendations, key=lambda x: x[0])
    s = sorted(t, key=lambda x: x[1], reverse=True)
    # [('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Cameron Tucker', 1), ('Manny Delgado', 1)]
    

    Note that Cameron Tucker comes before Manny Delgado now. All this and more is covered in detail in the excellent Sorting Howto

提交回复
热议问题