Python比较运算符从左到右链接/分组? [英] Python comparison operators chaining/grouping left to right?
问题描述
运算符优先级的Python文档状态:
The Python documentation for operator precedence states:
运算符在同一个框组中从左到右(
比较除外,包括测试,它们都有相同的优先级和
链从左到右 - 参见比较...)[ https://docs.python.org/2/reference/expressions.html#operator-precedence]
这是什么意思?具体来说:
What does this mean? Specifically:
-
Q1:运算符在同一个盒组中从左到右(
比较除外) - 从左到右进行比较不是?
Q2:如果
比较从左到右不是 Do
他们链而不是组?
Q2: If comparisons do not group left to right, what do they do instead? Do they "chain" as opposed to "group"?
Q3:如果比较chain
而不是group,chaining和
Q3: If comparisons "chain" rather than "group", what is the difference between "chaining" and "grouping"?
Q4:什么是一些例子来证明比较运算符从左到右,而不是从右到左?
Q4: What would be some examples to demonstrate that the comparison operators chain from left to right rather than from right to left?
推荐答案
分组(这是非比较运算符):
Grouping (this is what non-comparison operators do):
a + b + c means (a + b) + c
链接(这是比较运算符所做的):
Chaining (this is what comparison operators do):
a < b < c means (a < b) and (b < c)
是分组的方式):
5 - 2 - 1 means (5 - 2) - 1 == 2
而不是从右到左分组(这将产生不同的结果):
as opposed to grouping right to left (this would produce a different result):
5 - (2 - 1) == 4
b $ b
(编辑)
(edit)
链接是从左到右,因此在 b < c
,表达式 a < b
在 b < c
,如果 a < b
为false, b < c
Chaining is left to right, so in a < b < c
, the expression a < b
is evaluated before b < c
, and if a < b
is false, b < c
is not evaluated.
(2 <1 <无义)
值 False
,因为从不评估(1 <无义)
。
(无义> 1> 2)
引发错误,尝试评估(无意义> 1)
(2 < 1 < nonsense)
gives the value False
because (1 < nonsense)
is never evaluated.
(nonsense > 1 > 2)
raises an error trying to evaluate (nonsense > 1)
https://en.wikipedia.org/wiki/Short- circuit_evaluation
这篇关于Python比较运算符从左到右链接/分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!