(a)与(b)之间的差异;(b中不是a)。python

(a)与(b)之间的差异;(b中不是a)。python,python,Python,大家好,有人能解释一下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 pri

大家好,有人能解释一下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 ???
我现在想知道怎么会这样。如果有人知道,请分享你的知识。
谢谢=)

关键字
not
基本上“反转”了此处返回的布尔值

对于第一个示例,
a
在数组中,因此这是正确的,但是
not-true
是错误的。太假了

对于第二个示例,
a
不在数组中,因此为false,但
notfalse
为true。没错。

打印(在['a','b']中不是'a')

把它分解成这样:

not'a'
本身的计算结果为
False
(因为除0、无、False、空列表和空字典外,任何内容都被视为
True

false
不在
['a','b']
so中 ['a','b']中的
False
计算结果为
False


最后一个
not'a'
的计算结果为
False
,因此
False在['b',False]
中的计算结果为
True

。因此,执行安全壳检查,然后根据需要否定结果<代码>'a'
不在
['b',False]
中,结果
False
被求反,结果是
True

a不在
中和
不在
中是相等的。请注意,python样式指南说您应该使用
a不在
中,即使它们也一样。您可以很容易地将其更改为
(不是'a')['b',False]
这将为您提供您显然期望的答案(因为parens总是表示更高的优先级)将诸如
not a in b
之类的语句转换为
a not in b
。因此,这是使用
not in
的另一个原因,在我看来也是可读性很强的。这种解释是错误的。它没有考虑运算符的优先级。