与Python的in操作符有关的混乱

时间:2020-07-31 12:28:40

标签: python

我发现Python的in运算符有奇怪的行为

d = {}
'k' in d == False # False! 

我认为是因为优先考虑

('k' in d) == False # True, it's okay
'k' in (d == False) # Error, it's also okay

但是,什么优先级计算以下表达式呢?

d = {}
'k' in d == False

如果是由于错误的优先级,为什么它不会触发类似if的错误:

'k' in (d == False)

换句话说,用这个表达式在Python的幕后会发生什么?

'k' in d == False

1 个答案:

答案 0 :(得分:23)

in被认为是比较运算符,因此需要进行比较链接。

'k' in d == False

等同于

'k' in d and d == False

因为in==都是比较运算符。

实际上,您从不需要直接与布尔文字进行比较。这里的“正确”表达式为'k' not in d


作为参考,这在Python文档的6.10. Comparisons下进行了描述:

comparison    ::=  or_expr (comp_operator or_expr)*
comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="
                   | "is" ["not"] | ["not"] "in"

比较可以任意链接,例如,x