【问题标题】:cmp(list1,list2) function does not exist in Python [duplicate]python中不存在cmp(list1,list2)函数[重复]
【发布时间】:2020-03-25 02:57:08
【问题描述】:

cmp(list1,list2) 在 Python 3.x 中不受支持,而在 Python 2.x 中受支持。Python 3.x 中是否有 cmp() 函数的替代方法?

【问题讨论】:

标签: python


【解决方案1】:

作为远离 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2021-07-10
    相关资源
    最近更新 更多