Search code examples
pythonsortingtuplescomparison

Alternating-direction tuple sort with key function in python


I need to sort a list of tuples (length 2) but specifically need it to sort by second value descending and then by first value ascending. i.e. (0,1)<(1,1)<(1,0)

I think I could do it without too much trouble with a comparison function, but would like to know if it's doable with a key function.


Solution

  • You could use a lambda key as follows:

    tlist = [
        (1,1),
        (0,1),
        (1,0)
    ]
    
    print(sorted(tlist, key=lambda x: (-x[1], x[0])))
    

    Output:

    [(0, 1), (1, 1), (1, 0)]
    

    Or, without lambda...

    def cf(t):
        a, b = t
        return -b, a
    
    print(sorted(tlist, key=cf))