关于python:区间比较如何工作?

How does interval comparison work?

不知何故,这是可行的:

1
2
3
4
5
def in_range(min, test, max):
    return min <= test <= max

print in_range(0, 5, 10)  # True
print in_range(0, 15, 10)  # False

但是,我不太清楚这里的操作顺序。让我们测试一下False案例:

1
2
3
print 0 <= 15 <= 10  # False
print (0 <= 15) <= 10  # True
print 0 <= (15 <= 10)  # True

显然,这并不能解决简单的操作顺序问题。间隔比较是一个特殊的运算符,还是正在进行其他操作?


与大多数语言不同,Python支持链式比较运算符,并像在普通数学中那样对它们进行评估。

这条线:

1
return min <= test <= max

由python进行评估,如下所示:

1
return (min <= test) and (test <= max)

然而,大多数其他语言都会这样评价它:

1
return (min <= test) <= max


如python文档中所述:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.