【发布时间】:2014-10-28 16:51:12
【问题描述】:
您好,有人能解释一下 Python 中“in”运算符的工作机制吗?
我现在正在处理以下示例:
print ('a' not in ['a', 'b']) # outputs False
print (not 'a' in ['a', 'b']) # outputs False -- how ???
print ('c' not in ['a', 'b']) # outputs True
print (not 'c' in ['a', 'b']) # outputs True
print (not 'a') # outputs False
# ok is so then...
print (not 'a' in ['b', False]) # outputs True --- why ???
我现在想知道为什么会这样。如果有人知道,请分享您的知识。 谢谢=)
【问题讨论】:
-
a not in和not a in相等 -
请注意,python 样式指南说您应该使用
a not in,即使它们的作用相同。 -
您可以轻松地将其更改为
(not 'a') in ['b', False],这将为您提供您显然期望的答案(因为括号始终表示更高的优先级) -
peephole optimizer 将
not a in b等语句转换为a not in b。所以,这是使用not in的另一个原因,它在 IMO 上也具有很高的可读性。
标签: python