How to customize my own compare function in Python 3

Viewed 46

is there a way to customize a compare function in Python 3? For example, there is a list: [[1, a], [1, b], [2, b], [2, a], [3, a]]. First, sort it based on the integer, greater to smaller, then if the integer is the same, sort it based on the letters, in a dictionary order. It's completely two different order, first one is reversed and the second one is not. So I cannot just use 'reverse = True' to handle it.

I know there's cmp in Python 2 to help me define my own compare function. But how can I do it in Python 3?

Any help will be appreciated. Thank you

1 Answers

You can use a key function that returns a tuple of the items you want to sort by. Negate the numeric items for reverse order:

l = [[1, 'a'], [1, 'b'], [2, 'b'], [2, 'a'], [3, 'a']]
print(sorted(l, key=lambda t: (-t[0], t[1])))

This outputs:

[[3, 'a'], [2, 'a'], [2, 'b'], [1, 'a'], [1, 'b']]
Related