Closed. This question is off-topic。它目前不接受答案。
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
5年前关闭。
def compare(a, b):
    """
    Return 1 if a > b, 0 if a equals b, and -1 if a < b
    >>> compare (5, 7)
    1
    >>> compare (7, 7)
    0
    >>> compare (2, 3)
    -1
    """

最佳答案

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


>>> compare(5, 7)
-1
>>> compare(7, 7)
0
>>> compare(3, 2)
1

更长、更详细的方法是:
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

第一个解决办法是走自己的路,记住is pythonic to treat bools like ints
还要注意,Python 2有一个cmp函数,它可以执行以下操作:
>>> cmp(5, 7)
-1

然而,在Python 3中,由于通常用于比较的比较(例如,cmp现在使用list.sort函数而不是key)已不复存在。

10-05 20:48
查看更多