“a<b<c”是有效的python吗?

2024-05-19 16:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我很好奇是否可以使用这个a<b<c作为条件,而不使用标准的a<b and b<c。所以我试了一下,结果通过了。

a = 1
b = 2
c = 3

assert(a<b<c) # In bounds test
assert(not(b<a<c)) # Out of bounds test
assert(not(a<c<b)) # Out of bounds test

为了更好的衡量,我尝试了更多的数字,这次是在负区域。其中a, b, c = -10, -9, -8。考试又通过了。即使是在更高范围内的测试服也能工作。甚至是a, b, c = 10, 20, 5

和C++中的同样的实验。我就是这么想的:

#include <iostream>

using namespace std;

int main()
{
    int a,b,c;
    a=10;
    b=20;
    c=5;
    cout << ((a<b<c)?"True":"False") << endl; // Provides True (wrong)
    cout << ((a<b && b<c)?"True":"False") << endl; // Provides False (proper answer)
    return 0;
}

我最初认为这个实现是无效的,因为在我遇到的所有其他语言中,在布尔值到达c之前,它都会求值。使用这些语言,a<b将求值为布尔值,并且继续求值,b<c将无效,因为它将尝试对数字求值布尔值(很可能引发编译时错误或伪造预期的比较)。不知什么原因,这让我有点不安。我想我只需要确信这是语法的一部分。在Python文档中提供这个特性的位置的参考也会很有帮助,这样我就可以看到它们在多大程度上提供了这样的特性。


Tags: oftest语言falsetruenot数字特性
3条回答

a<;b<;c
执行如下

(a<;b)<;c
(假)<;c=>;(0)<;c
是的。。。。。
这是为你而发生的

这是有记录的here

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.

作为一个例子

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).

Python“自然地”链接关系运算符。请注意,Python的关系运算符包括inis(以及它们的负数),这在将它们与符号关系运算符混合时可能会导致一些令人惊讶的结果。

相关问题 更多 >