如何在Python 3中使用cmp()?
我在Python 3中无法让命令cmp()
正常工作。
这是我的代码:
a = [1,2,3]
b = [1,2,3]
c = cmp(a,b)
print (c)
我遇到了这个错误:
Traceback (most recent call last):
File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module>
c = cmp(a,b)
NameError: name 'cmp' is not defined
9 个回答
0
在一般情况下,这些都是很好的替代方案,可以用来替换 cmp()
函数。不过,对于最初提问者的具体情况,
a = [1,2,3]
b = [1,2,3]
c = a != b
print(c)
或者直接用
a = [1,2,3]
b = [1,2,3]
print(a != b)
也会效果很好。
0
补充一下@maxin的回答,在python 3.x
中,如果你想比较两个包含元组的列表a
和b
import operator
a = [(1,2),(3,4)]
b = [(3,4),(1,2)]
# convert both lists to sets before calling the eq function
print(operator.eq(set(a),set(b))) #True
1
当需要处理符号时,最安全的选择可能是使用 math.copysign:
import math
ang = -2
# alternative for cmp(ang, 0):
math.copysign(1, ang)
# Result: -1
特别是当 ang 是 np.float64 类型时,因为 '-' 操作符可能会被弃用。
例如:
import numpy as np
def cmp_0(a, b):
return (a > b) - (a < b)
ang = np.float64(-2)
cmp_0(ang, 0)
# Result:
# DeprecationWarning: numpy boolean subtract, the `-` operator, is deprecated,
# use the bitwise_xor, the `^` operator, or the logical_xor function instead.
你也可以使用:
def cmp_0(a, b):
return bool(a > b) - bool(a < b)
ang = np.float64(-2)
cmp(ang, 0)
# Result: -1
14
在Python 3.x中,你可以使用 import operator
来引入一个叫做 operator 的模块,然后用这个模块里的 eq()
、lt()
等函数来代替以前的 cmp()
函数。
111
正如评论中提到的,cmp
在 Python 3 中是不存在的。如果你真的需要这个功能,可以自己定义一个:
def cmp(a, b):
return (a > b) - (a < b)
这个内容来自于原始的 Python 3.0 新特性。不过其实这种需求很少见,虽然不是完全没有。所以你可能需要考虑一下,这是否真的是你想要做事情的最佳方法。