为什么 `a<b<c` 在 Python 中有效?
Why does `a<b<c` work in Python?
标题说明了一切。例如 1<2<3
returns True
和 2<3<1
returns False
。
它很好用,但我无法解释为什么它会起作用...我在文档中找不到任何相关信息。它总是:expression boolean_operator expression
,而不是两个布尔运算符)。另外: a<b
returns 一个布尔值, boolean boolean_operator expression
不解释行为。
我确定解释(几乎)显而易见,但我似乎错过了。
这称为运算符链接。文档位于:
https://docs.python.org/2/reference/expressions.html#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.
您的多个运算符都具有相同的优先级,因此现在将按顺序处理它们。 1<2<3
到1<2
是T,然后2<3
是T。2<3<1
有两部分,2<3
是T,但3<1
是F所以整个表达式的计算结果为 F.
根据语言参考,可以链接比较运算符
标题说明了一切。例如 1<2<3
returns True
和 2<3<1
returns False
。
它很好用,但我无法解释为什么它会起作用...我在文档中找不到任何相关信息。它总是:expression boolean_operator expression
,而不是两个布尔运算符)。另外: a<b
returns 一个布尔值, boolean boolean_operator expression
不解释行为。
我确定解释(几乎)显而易见,但我似乎错过了。
这称为运算符链接。文档位于:
https://docs.python.org/2/reference/expressions.html#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 andop1
,op2
, ...,opN
are comparison operators, thena op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.
您的多个运算符都具有相同的优先级,因此现在将按顺序处理它们。 1<2<3
到1<2
是T,然后2<3
是T。2<3<1
有两部分,2<3
是T,但3<1
是F所以整个表达式的计算结果为 F.
根据语言参考,可以链接比较运算符