检查列表中是否存在项目时,为什么此代码不起作用 - 如果列表中的项目== False:

Rag*_*dar 4 python

考虑这个清单:

list = [1,2,3,4,5]
Run Code Online (Sandbox Code Playgroud)

我想检查此列表中是否不存在数字9.有两种方法可以做到这一点.

方法1:此方法有效!

if not 9 in list: print "9 is not present in list"
Run Code Online (Sandbox Code Playgroud)

方法2:此方法不起作用.

if 9 in list == False: print "9 is not present in list"
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么方法2不起作用?

Mar*_*ers 16

这是由于比较运算符链接.从文档:

比较可以任意链接,例如,x < y <= z等同于x < y and y <= z,除了y仅评估一次(但在两种情况下z都没有被评估,当x < y发现是假的时).

您假设9 in list == False表达式被执行,(9 in list) == False但事实并非如此.

相反,python会将其评估为(9 in list) and (list == False)相反,而后者则永远不会为True.

您真的想使用not in运算符,并避免命名变量list:

if 9 not in lst:
Run Code Online (Sandbox Code Playgroud)