(a not in b) 和 (not a in b) 的区别。Python

5

你好,能否有人解释一下 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 ???

我现在很想知道为什么会这样。如果有人知道,请分享你的知识。 谢谢 =)


5
a not innot a in 是等价的。 - Tim
2
请注意,Python风格指南建议您使用a not in,即使它们的作用相同。 - Tim
你可以轻松将其更改为(not 'a') in ['b', False],这将给出你期望的答案(因为括号始终表示更高的优先级)。 - Joran Beasley
Peephole优化器将类似于not a in b的语句转换为a not in b。因此,这是使用not in的另一个原因,而且在我看来更易读。 - Ashwini Chaudhary
3个回答

9

in的优先级高于not。因此,如果需要,先执行包含检查,然后再否定结果。'a'不在['b', False]中,所以结果为False,再将其取反得到True


2

not 关键词基本上"反转"了这里返回的布尔值。

对于第一个例子,a 在数组中,所以是真的,但 not true 是假的。所以是假的。

对于第二个例子,a 不在数组中,所以是假的,但 not false 是真的。所以是真的。


-1

print (not 'a' in ['a', 'b'])

将其分解如下:

not 'a'本身就会被评估为False(因为除了0、None、False、空列表和空字典之外,任何东西都被认为是True

并且False不在['a','b']中,所以False in ['a','b']评估为False

最后一个not 'a'评估为False,所以False in ['b', False]评估为True


这个解释是错误的。它没有考虑运算符的优先级。 - stenci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接