[英]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 : 我已经在Python2中编写了一种排序方式,我正在尝试将其转换为Python3并要求输入密钥,并说不再有cmp函数可用:
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. 官方python 3文档在本节中说明了将其从python 2转换为3的正确方法。
The original cmp
function simply does something like 原始的
cmp
函数只是执行以下操作
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. 也就是说,它等效于
sign(xy)
,但也支持字符串和其他数据类型。
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. 但是,您的问题是当前的
sort
函数不适用于带有两个参数的比较函数,而不能与一个参数的单个key
函数一起使用。 Python provides functools.cmp_to_key
to help you convert it, so, do something like Python提供了
functools.cmp_to_key
来帮助您转换它,因此,请执行类似的操作
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])
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.