Python cmp()函数

2024-10-03 09:18:04 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在尝试使用cmp()函数比较python中的两个元组 但出现了一个错误,错误如下:

名称错误:未定义名称“cmp”

我的代码:

myStupidTup = ("test",10,"hmm",233,2,"am long string")
mySmartTup = ("test",10,233,2)
print(cmp(myStupidTup, mySmartTup)) 

Tags: 函数代码test名称string错误amlong
1条回答
网友
1楼 · 发布于 2024-10-03 09:18:04

^{}函数仅在Python 2.x中。如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中的^{}等价物是:

def cmp(a, b):
    return (a > b) - (a < b) 

注意:元组(myStupidTupmySmartTup)不支持比较。如果运行它,您将得到一个TypeErrorTypeError: '>' not supported between instances of 'str' and 'int'

相关问题 更多 >