<分区>
以下代码输出 False,根据 Python 操作顺序它应该输出 True(顺序应该是 -> ==,而不是相反)。为什么 == coming before in?
y = "33"
"3" in y == True
输出
False
标签 python
<分区>
以下代码输出 False,根据 Python 操作顺序它应该输出 True(顺序应该是 -> ==,而不是相反)。为什么 == coming before in?
y = "33"
"3" in y == True
输出
False
最佳答案
现有答案提供了有用的建议,您不应将 bool 值与 True
进行比较因为它是多余的。但是,没有一个答案真正回答了根本问题:“为什么 "3" in y == True
的计算结果为 False
?”。
juanpa.arrivillaga 在评论中回答了这个问题:
Also, this is an instance of operator chaining, since
==
andin
both count as comparison operators. So this is evaluated as('3' in y) and (y == True)
在 Python 中,比较运算符可以链接。例如,如果你想检查 a
, b
, c
, 和 d
正在增加,你可以写a < b < c < d
而不是 a < b and b < c and c < d
.同样,您可以使用 a == b == c == d
检查它们是否都相等.
链式比较在 Python 文档中描述 here :
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).
关于python - 为什么在 Python 中是 ‘==‘ coming before ‘in’?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53412942/