Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何编写比较函数? def比较(a,b): """ 如果a>b,则返回1;如果a等于b,则返回0;如果a>>比较(5,7) 1. >>>比较(7,7) 0 >>>比较(2,3) -1 """_Python_Python 2.7_Doctest - Fatal编程技术网 b,则返回1;如果a等于b,则返回0;如果a>>比较(5,7) 1. >>>比较(7,7) 0 >>>比较(2,3) -1 """,python,python-2.7,doctest,Python,Python 2.7,Doctest" /> b,则返回1;如果a等于b,则返回0;如果a>>比较(5,7) 1. >>>比较(7,7) 0 >>>比较(2,3) -1 """,python,python-2.7,doctest,Python,Python 2.7,Doctest" />

Python 如何编写比较函数? def比较(a,b): """ 如果a>b,则返回1;如果a等于b,则返回0;如果a>>比较(5,7) 1. >>>比较(7,7) 0 >>>比较(2,3) -1 """

Python 如何编写比较函数? def比较(a,b): """ 如果a>b,则返回1;如果a等于b,则返回0;如果a>>比较(5,7) 1. >>>比较(7,7) 0 >>>比较(2,3) -1 """,python,python-2.7,doctest,Python,Python 2.7,Doctest,当它展平时,看起来像: def compare(a, b): return 1 if a > b else 0 if a == b else -1 第一个解决方案是要走的路,记住这一点 还要注意的是,Python 2有一个cmp函数,它执行以下操作: def compare(a, b): if a > b: return 1 elif a == b: return 0 else: return -1

当它展平时,看起来像:

def compare(a, b):
    return 1 if a > b else 0 if a == b else -1
第一个解决方案是要走的路,记住这一点

还要注意的是,Python 2有一个
cmp
函数,它执行以下操作:

def compare(a, b):
    if a > b:
        return 1
    elif a == b:
        return 0
    else:
        return -1

然而,在Python 3中,
cmp
已经不存在了,因为它通常用于比较,例如
列表。排序现在使用
函数而不是
cmp

来进行,如果您编写比较函数以便将其传递给
排序
,则您的示例是错误的,此做法已被弃用-改为编写一个
函数,它既不弃用,也更快。另外请注意,此函数已作为内置的
cmp
def compare(a, b):
    return 1 if a > b else 0 if a == b else -1
def compare(a, b):
    if a > b:
        return 1
    elif a == b:
        return 0
    else:
        return -1
>>> cmp(5, 7)
-1