Search code examples
pythonpython-3.xsortingcomparison

How to efficiently define custom global comparator in Python 3?


I want to define comparator like:

def cmp_smth(x, y):
    if x == y:
        return 0
    elif fn(x, y):
        return -1
    else:
        return 1
comparator = functools.cmp_to_key(cmp_smth)

And it works fine with cmp_to_key converter, i.e.:

sorted([x, y, z], key=comparator)

But what if I want to sort something more complicated, i.e. tuples:

sorted([(1, x), (2, y), (3, z)], key=???)

How to use my global comparator in this case?


Solution

  • You can use a lambda to map you key function (previously a comparator) to the second element of each tuple:

    sorted([(1, x), (2, y), (3, z)], key=lambda x: comparator(x[1]))