If you are familiar with some builtin high-order functions and methods such as sorted()
, filter
, min()
, max()
, reduce()
, etc, you might already be familiar with how key function works.
A key function allows you to define a specific criteria to be used for establishing order in a collection of items. Typically, key functions takes a single argument and returns a value that the sorting or ordering algorithm will use to compare elements in the collection.
How cmp_to_key() function works
The cmp_to_key()
function converts a comparison function to a key function which can be used as an ordering criteria. Typically, a comparison function takes two arguments and returns a negative( usually -1), zero, or positive( usually 1) number depending on whether the comparison operation evaluates to False, equal, or True, respectively.
@cmp_to_key def cmp_func(x, y): #statements or def cmp_func(x, y): #statements key_func = cmp_to_key(func)
copy
If the comparison function has already been defined or for some reason you do not want to use the @ decorator syntax, you can achive the same as shown below.