Custom function for the function sorted in python 3.x

0

In python 2.x I can pass a custom function to sorted function, how to do this in python 3.x?

Basically convert the code below

def numeric_compare(x, y):
    return x - y

print(sorted([5, 2, 4, 1, 3], cmp=numeric_compare) )
    
asked by anonymous 02.01.2018 / 02:40

1 answer

2

Use the cmp_to_key method of the functools library It will look like this:

import functools
def numeric_compare(x, y):
    return x - y

print(sorted([5, 2, 4, 1, 3], key=functools.cmp_to_key(numeric_compare)))
    
02.01.2018 / 03:18