Python cmp() 函数
Python cmp() function
您好,我正在尝试使用 cmp() 函数比较 python 中的两个元组
但是出现以下错误:
NameError: 名称 'cmp' 未定义
我的代码:
myStupidTup = ("test",10,"hmm",233,2,"am long string")
mySmartTup = ("test",10,233,2)
print(cmp(myStupidTup, mySmartTup))
cmp
function is only in Python 2.x
. As mentioned in the official Python documentation:
The cmp()
function should be treated as gone, and the __cmp__()
special method is no longer supported. Use __lt__()
for sorting, __eq__()
with __hash__()
, and other rich comparisons as needed. (If you really need the cmp()
functionality, you could use the expression (a > b) - (a < b)
as the equivalent for cmp(a, b)
.)
Python 3.x
中的 cmp
等价于:
def cmp(a, b):
return (a > b) - (a < b)
注意:您的元组(myStupidTup
和 mySmartTup
)不支持比较。如果你运行你会得到一个TypeError
:TypeError: '>' not supported between instances of 'str' and 'int'
您好,我正在尝试使用 cmp() 函数比较 python 中的两个元组 但是出现以下错误:
NameError: 名称 'cmp' 未定义
我的代码:
myStupidTup = ("test",10,"hmm",233,2,"am long string")
mySmartTup = ("test",10,233,2)
print(cmp(myStupidTup, mySmartTup))
cmp
function is only in Python 2.x
. As mentioned in the official Python documentation:
The
cmp()
function should be treated as gone, and the__cmp__()
special method is no longer supported. Use__lt__()
for sorting,__eq__()
with__hash__()
, and other rich comparisons as needed. (If you really need thecmp()
functionality, you could use the expression(a > b) - (a < b)
as the equivalent forcmp(a, b)
.)
Python 3.x
中的 cmp
等价于:
def cmp(a, b):
return (a > b) - (a < b)
注意:您的元组(myStupidTup
和 mySmartTup
)不支持比较。如果你运行你会得到一个TypeError
:TypeError: '>' not supported between instances of 'str' and 'int'