【发布时间】:2020-03-25 02:57:08
【问题描述】:
cmp(list1,list2) 在 Python 3.x 中不受支持,而在 Python 2.x 中受支持。Python 3.x 中是否有 cmp() 函数的替代方法?
【问题讨论】:
-
取决于你在做什么/使用它,还有
functools.cmp_to_key()。
标签: python
cmp(list1,list2) 在 Python 3.x 中不受支持,而在 Python 2.x 中受支持。Python 3.x 中是否有 cmp() 函数的替代方法?
【问题讨论】:
functools.cmp_to_key()。
标签: python
作为远离 cmp 样式比较的一部分,cmp() 函数在 Python 3 中被删除。
如果有必要(通常是为了符合外部 API),您可以提供此代码:
def cmp(x, y):
"""
Replacement for built-in function cmp that was removed in Python 3
Compare the two objects x and y and return an integer according to
the outcome. The return value is negative if x < y, zero if x == y
and strictly positive if x > y.
"""
return (x > y) - (x < y)
【讨论】: