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

2024-05-20 00:55:12 发布

您现在位置:Python中文网/ 问答频道 /正文

请考虑以下列表:

list = [1,2,3,4,5]

我想看看这个名单上是否没有9号。有两种方法可以做到这一点。

方法一:这个方法有效!

if not 9 in list: print "9 is not present in list"

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

if 9 in list == False: print "9 is not present in list"

有人能解释一下为什么方法2不起作用吗?


Tags: 方法infalse列表ifisnotlist
2条回答

应该是:

if (9 in list) == False: print "9 is not present in list"

这是由于comparison operator chaining。从文档中:

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).

假设9 in list == False表达式是作为(9 in list) == False执行的,但事实并非如此。

相反,python将其计算为(9 in list) and (list == False),而后一部分永远不是真的。

你真的想使用not in运算符,并且避免给变量命名list

if 9 not in lst:

相关问题 更多 >