Sort a list of tuples by value and then alphabetically

后端 未结 2 529
旧巷少年郎
旧巷少年郎 2021-01-19 01:36

Bit of a python newbie, but I got the following list of tuples. I need to sort it by value and if the value is the same, solve ties alphabetically. Here\'s a sample:

相关标签:
2条回答
  • 2021-01-19 02:27

    You can use the sorted function:

    sorted_by_medals = sorted(list_of_medals, key=lambda tup: (-tup[1], tup[0]))
    
    0 讨论(0)
  • 2021-01-19 02:39

    In this instance, I'd use a lambda function as the key argument to sort()/sorted():

    In [59]: sorted(list_of_medals, key=lambda x:(-x[1],x[0]))
    Out[59]: 
    [('Sweden', 24),
     ('Germany', 16),
     ('Ireland', 10),
     ('Russia', 10),
     ('Spain', 9),
     ('Albania', 8),
     ('Lithuania', 7),
     ('Iceland', 6),
     ('Italy', 5),
     ('Malta', 5),
     ('Estonia', 4),
     ('Serbia', 4),
     ('Turkey', 4),
     ('Azerbaijan', 2),
     ('Moldova', 2)]
    

    The negation of x[1] is needed to sort the medals in descending order while sorting country names in ascending order (simply setting reverse=True wouldn't achieve that).

    As several people have pointed out in the comments, a more general way to do a complex sort on a compound key is to perform several sorting steps. To do this, sort on one component at a time, starting with the least significant one:

    In [67]: temp = sorted(list_of_medals, key=itemgetter(0))
    
    In [68]: sorted(temp, key=itemgetter(1), reverse=True)
    Out[68]: 
    [('Sweden', 24),
     ('Germany', 16),
     ('Ireland', 10),
     ('Russia', 10),
     ...
    

    This relies on the fact that Python's sort is stable, meaning that items that compare equal are never reordered.

    0 讨论(0)
提交回复
热议问题