Convert sort from Python2 to Python3

1.6k Views Asked by At

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,

1

There are 1 best solutions below

0
On

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