Python sorting key function supporting tuples and lists

后端 未结 4 707
你的背包
你的背包 2021-01-22 08:09

In Python you can for example sort tuples sorted([(2,2),(1,2),(2,1),(1,1)]) and get [(1, 1), (1, 2), (2, 1), (2, 2)].

You can also use custom k

4条回答
  •  青春惊慌失措
    2021-01-22 08:30

    You don't need a extra function. You can also do it:

    medals_map = {'Gold': 1, 'Silver': 2, 'Bronze': 3 }
    List = [('Bronze', 1), ('Gold', 1), ('Gold', 2)]
    
    new_list = sorted(List, key=lambda word: (medals_map[word[0]], word[1]))
    
    print new_list
    

    Output:

    [('Gold', 1), ('Gold', 2), ('Bronze', 1)]
    

提交回复
热议问题