Python 顺序优先级(在 vs "==" 中)



>有人有描述为什么这是给出的行为吗?

if (key in self.dict) == True:

if key in self.dict == True:

我的优先级顺序表告诉我这两个运算符应该从左到右计算,但由于某种原因,我实际上在我给出的第二个示例中看到了不正确的行为。 有谁知道为什么括号在这里很重要?

https://docs.python.org/3/reference/expressions.html#operator-precedence

据我了解,这两条线的评价应该完全相同。

可重现:

Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dict = {}
>>> dict[1] = 2
>>> 1 in dict
True
>>> 1 in dict == True
False
>>> (1 in dict) == True
True
>>> 1 in (dict == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

相关部分是比较:

比较可以任意链接,例如,x<= z 是等价的 到 x<= z

所以你有

key in dict and dict == True

这是一个非常独特的Python东西。

最新更新