pythonlistsortingnumbersalphabet

How to sort a list by number first in descending order and then by alphabet in ascending order


I have a list

ff = [('o', 2), ('l', 1), ('e', 1), ('g', 2)]

and i want to sort it in such a way in which it get sorted by number in descending order and if any element have same number then it get sorted by alphabet in ascending order, like this

ff = [('g', 2), ('o', 2), ('e', 1), ('l', 1)]

Solution

  • You can use sorted with parameter key:

    ff = [('o', 2), ('l', 1), ('e', 1), ('g', 2)]
    
    output = sorted(ff, key=lambda x: (-x[1], x[0]))
    
    print(output) # [('g', 2), ('o', 2), ('e', 1), ('l', 1)]
    

    When a tuple is given as key, sorted sorts the list lexicographically. In this case it first sorts according to the second element in descending order (-x[1]) and then sorts according to the first element in ascending order (x[0]).