I've written a sort in Python2, I'm trying to convert it into Python3 which asks for a key and says no more cmp function is available :
test.sort(lambda x, y: cmp(x[2],y[2]) or cmp(x[4], y[4]) or cmp(y[9], x[9]))
Any advices ?
Best regards,
The official python 3 documentation explains in this section the proper way of converting this from python 2 to 3.
The original cmp function simply does something like
def cmp(x, y):
if x == y:
return 0
elif x > y:
return 1
else:
return -1
That is, it's equivalent to sign(x-y), but also supports strings and other data types.
However, your problem is that the current function of sort doesn't work with a comparison function with two arguments, but with a single key function of one argument. Python provides functools.cmp_to_key to help you convert it, so, do something like
test.sort(key = functools.cmp_to_key(
lambda x, y: cmp(x[2],y[2]) or cmp(x[4], y[4]) or cmp(y[9], x[9])
))
key=lambda L: (L[2], L[4], L[9])so you get some sort of "order" there?cmpfunction, and 2) Making thesortwork with akey=function. Those two separate problems have two separate answers, so in the future please ask about each problem individually.test? Eg, is it a list of lists, or a list of tuples?