python 中的布尔比较

Boolean comparison in python

Python 似乎用(我认为的)奇怪地评估了相对简单的语法。任何人都可以阐明这里幕后发生的事情吗? python 认为第一种情况发生了什么?

>>> x = 'foo'
>>> 'f' in x == True
False
>>> ('f' in x) == True
True
>>> 'f' in (x == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

你在这里看到的是chained comparisons:

'f' in x == True

in==都是比较。现在 Python 使用 implicit and 解释 chained 比较解释器。所以你基本上写了:

'f' in x and x == True

第二次检查失败。

如果你写:

a < b in c

它是以下简称:

a < b and b in c

(除了表达式只计算一次)。

如果我们查看文档,我们会看到有 11 个比较器:

comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
                   | "is" ["not"] | ["not"] "in"

此外它指出:

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.