这个问题在这里已经有了答案:
Unexpected result from `in` operator - Python [duplicate]
(3 个回答)
去年关闭。
我发现 Python 的 in
有奇怪的行为运算符(operator)
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
如果是因为优先级错误,为什么它不会触发错误,例如:'k' in (d == False)
换句话说,这个表达式在 Python 的底层发生了什么?'k' in d == False
最佳答案
in
被认为是一个比较运算符,因此它受比较链的影响。
'k' in d == False
相当于'k' in d and d == False
因为两者 in
和 ==
是比较运算符。不过,您几乎不需要直接与 bool 文字进行比较。这里的“正确”表达式是
'k' not in d
.作为引用,这在 6.10. Comparisons 下的 Python 文档中有所描述。 :
comparison ::= or_expr (comp_operator or_expr)* comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in"
和
Comparisons can be chained arbitrarily, e.g., 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).
关于python - 与 Python 的 `in` 运算符相关的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63191845/