cmp to key
suggest changePython changed its sorting methods to accept a key function. Those functions take a value and return a key which is used to sort the items.
Old comparison functions used to take two values and return -1, 0, or +1 if the first argument is smaller than, equal to, or greater than the second argument respectively. This is incompatible with the new key function.
That’s where functools.cmp_to_key comes in:
>>> import functools
>>> import locale
>>> sorted(["A", "S", "F", "D"], key=functools.cmp_to_key(locale.strcoll))
['A', 'D', 'F', 'S']
Example taken and adapted from the Python Standard Library Documentation.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents