x in range(...) == y 在 Python 3 中是什么意思? [英] What does x in range(...) == y mean in Python 3?
问题描述
我刚刚在 Python 3 中偶然发现了以下行.
1 in range(2) == True
我期望这是 True
,因为 1 in range(2)
为 True,True == True
为 True.>
但这会输出False
.所以它和 (1 in range(2)) == True
的意思不一样.此外,它与引发错误的 1 in (range(2) == True)
并不相同.
尽管有多年 Python 经验,我还是措手不及.这是怎么回事?
这是因为两个运算符都是比较运算符,因此被解释为运算符链接:
https://docs.python.org/3.6/reference/expressions.html#comparisons
<块引用>比较可以任意链接,例如,x <;y <= z
是等价的到 x
y
只计算一次(但在两个case z
在 x <;y
被发现是假的).
所以等价于:
<预><代码>>>>(1 in range(2)) 和 (range(2) == True)错误的I just stumbled upon the following line in Python 3.
1 in range(2) == True
I was expecting this to be True
since 1 in range(2)
is True and True == True
is True.
But this outputs False
. So it does not mean the same as (1 in range(2)) == True
. Furthermore it does not mean the same as 1 in (range(2) == True)
which raises an error.
Despite years of experience in Python, I am taken off guard. What is going on?
This is due to the fact that both operators are comparison operators, so it is being interpreted as operator chaining:
https://docs.python.org/3.6/reference/expressions.html#comparisons
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
So it is equivalent to:
>>> (1 in range(2)) and (range(2) == True)
False
这篇关于x in range(...) == y 在 Python 3 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!