Custom Order with functools.cmp_to_key
Write a comparator when keys fall short.
When a key Cannot Express It
Some orders depend on comparing two items together, not one value each. For those, you write a comparator function instead of a key.
What a Comparator Returns
A comparator takes two items a and b. Return a negative number if a comes first, positive if b comes first, and zero if they tie.
def cmp(a, b):
if a < b: return -1
if a > b: return 1
return 0All lessons in this course
- sorted() and the key Function
- Sort by Multiple Fields
- Custom Order with functools.cmp_to_key
- Why Sorting First Unlocks Solutions