简体   繁体   中英

Convert sort from Python2 to Python3

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(xy) , 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])
)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM