gpt4 book ai didi

python - 为什么 cmp() 有用?

转载 作者:IT老高 更新时间:2023-10-28 21:16:25 28 4
gpt4 key购买 nike

根据doc这个tutorial ,

cmp() returns -1 if x < y

cmp() returns 0 if x == y

cmp() returns 1 if x > y

教程里也说了

cmp() returns the sign of the difference of two numbers

我真的不明白 两个数字之差的符号 是什么意思。这是否意味着当数字的符号不相等时它会返回一个值?因为……

cmp(80, 100) :  -1      # both have positive sign.
cmp(180, 100) : 1 # both also have positive sign.
cmp(-80, 100) : -1
cmp(80, -100) : 1

**注意:教程中的代码。*

尽管我对符号差异感到困惑,但我真的想不出为什么我们需要一个内置函数来在 x < y 时返回值 -1。

不是函数 cmp( ) 容易实现? Python 创作者保留 cmp( ) 有什么原因吗?函数,或者这个 Python 的 cmp( ) 是否有任何隐藏用法 功能?

最佳答案

Why cmp( ) is useful?

它不是很有用,这就是它被弃用的原因(内置 cmp 已消失,内置排序在 Python 3 中不再接受)。 Rich comparison methods取代它:

object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

这允许 <符号(和其他符号)是重载的比较运算符,例如,可以对集合对象进行子集和超集比较。

>>> set('abc') < set('cba')
False
>>> set('abc') <= set('cba')
True
>>> set('abc') == set('cba')
True
>>> set('abc') >= set('cba')
True
>>> set('abc') > set('cba')
False

虽然它可以启用上述功能,cmp不允许以下行为:

>>> set('abc') == set('bcd')
False
>>> set('abc') >= set('bcd')
False
>>> set('abc') <= set('bcd')
False

cmp 的玩具用途

这是一个有趣的用法,它使用它的结果作为索引(如果第一个小于第二个,则返回 -1,如果相等则返回 0,如果大于则返回 1):

def cmp_to_symbol(val, other_val):
'''returns the symbol representing the relationship between two values'''
return '=><'[cmp(val, other_val)]

>>> cmp_to_symbol(0, 1)
'<'
>>> cmp_to_symbol(1, 1)
'='
>>> cmp_to_symbol(1, 0)
'>'

根据文档,您应该将 cmp 视为不存在:

https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons

cmp删除,等效操作

但是您可以将其用作等效项:

(a > b) - (a < b)

在我们的小玩具函数中,就是这样:

def cmp_to_symbol(val, other_val):
'''returns the symbol representing the relationship between two values'''
return '=><'[(val > other_val) - (val < other_val)]

关于python - 为什么 cmp() 有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15556813/

28 4 0