pythonsortingstable-sort

How can i sort a list by the second item descending and first one ascending?


I have a list like this:

list_results=[('Horror', 2), ('Romance', 2), ('Comedy', 2), ('History', 2), ('Adventure', 1), ('Action', 3)]

I wish to sort the number in descending order and if numbers were the same, according to the name in ascending order.

I tried the following code:

sortlist=sorted(list_results,key=lambda x:(x[1],x[0]))

and the reverse but I couldn't figure out to do it.

The answer that I'm looking for is:

[('Action', 3), ('Comedy', 2) ,('History', 2),('Horror', 2), ('Romance', 2), ('Adventure', 1), ]

Solution

  • First sort the list by the first item, then by the second item:

    list_results = sorted(list_results, key=lambda x:x[0])
    list_results = sorted(list_results, key=lambda x:x[1], reverse=True)
    

    or better yet without copying:

    import operator
    
    list_results.sort(key=operator.itemgetter(0))
    list_results.sort(key=operator.itemgetter(1), reverse=True)
    

    Python's sort algorithm is Timsort. It is a stable algorithm meaning if 2 values are the same, they'll stay in their original order.

    If you sort alphabetically first, and then by the priority, the list will be sorted according to the alphabet, then re-sorted according to priority with alphabet being secondary.