组合Python“in”和“==”运算符会产生令人困惑的行为

问题描述 投票:0回答:1

我的一个朋友正在学习Python,我看到他用他的代码做了一件奇怪的事情:

if ch in input[index] == test[index])

显然该片段缺少一些上下文,但有趣的是,该 if 语句给出了他想要的行为。同样,下面的语句打印

True
:

print("w" in "w" == "w")

我不是Python专家,所以我不明白为什么会发生这种情况。我会假设某种优先级和/或关联性会使这里的事情变得混乱并返回

False
或抛出错误。

据我所知,

"w" in "w" == "w"
"w" in "w" and "w"== "w"
相同,这是相当不直观的。我希望了解Python解释的人可以解释为什么这种语句以这种方式评估。

python operators operator-precedence
1个回答
0
投票

文档中明确说明了这一点(https://docs.python.org/3/reference/expressions.html#comparisons):

比较可以任意链接,例如 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).

在文档中使用的运算符是

<
<=
,但是
in
==
也是运算符,所以这也适用于问题中的情况:

"w" in "w" == "w"
评价为
"w" in "w" and "w" == "w"

© www.soinside.com 2019 - 2024. All rights reserved.