Py学习  »  Python

Python中“in”和“==”的优先级[重复]

nugget_boi • 4 年前 • 557 次点击  

假设我有以下代码行:

print("valley" in "hillside" == False)

因为 in == True 作为输出。

False .

我注意到在周围加括号 "valley" in "hillside" 结果 真的

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56970
 
557 次点击  
文章 [ 2 ]  |  最新文章 4 年前
finefoot
Reply   •   1 楼
finefoot    4 年前

查看Python文档中的表 https://docs.python.org/3/reference/expressions.html#operator-precedence 它总结了运算符优先级,您可以看到 in == 与其他一些运算符放在同一个框中:

in, not in, is, is not, <, <=, >, >=, !=, ==

随后它还说:

Comparisons 章节。

正式的,如果 a, b, c, ..., y, z op1, op2, ..., opN 是比较运算符,那么 a op1 b op2 c ... y opN z 相当于 a op1 b and b op2 c and ... y opN z ,但每个表达式最多只能计算一次。

因此,你的例子

"valley" in "hillside" == False

"valley" in "hillside" and "hillside" == False
chepner
Reply   •   2 楼
chepner    4 年前

两者 in == 是比较运算符,因此解析器处理

print("valley" in "hillside" == False)

一样

print("valley" in "hillside" and "hillside" == False)

请参阅 Comparisons 在《Python语言参考》中了解更多详细信息,特别是以下注意事项:

可以任意链接比较,例如x<y<=z等同于x<y和y<=z,但y只计算一次(但在这两种情况下,当x<y为false时,z根本不计算)。