Custom function for the Sorted function in python 3.x

Asked

Viewed 75 times

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) )

1 answer

2


Use the cmp_to_key method of the functools library Will stay this way:

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

print(sorted([5, 2, 4, 1, 3], key=functools.cmp_to_key(numeric_compare)))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.