all Python 3functoolsfunction
functools.cmp_to_key
functools
Convert an old-style cmp(a, b) comparison function into a key function for sorted().
Syntax
functools.cmp_to_key(func)
Reach for it only when the ordering cannot be expressed as a single key because the decision depends on a pair of elements at once — the classic case is arranging numbers to form the largest possible number. Otherwise a plain key= wins: the key is computed once per element, while a comparison function is called about n log n times through a wrapper object. Also, cmp must return a negative number, zero or a positive number — not True/False.
Examples
import functools
def cmp(a, b):
return a - b
print(sorted([3, 1, 2], key=functools.cmp_to_key(cmp))) # → [1, 2, 3]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy