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

标签 python

<分区>

考虑这个列表:

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

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

方法一:这个方法行得通!

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

方法二:这个方法不行。

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

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

最佳答案

这是由于 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:

关于python - 检查列表中是否不存在某个项目时,为什么此代码不起作用 - 如果列表中的项目 == False :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15336602/

相关文章:

python - 根据 Python 中的产品对列表中的元组进行排序

python - Spyder (Python 3.7) 启动时出现一个黑色窗口。我该如何修复它?

python - 添加整页图像作为reportlab的最后一页

python - 迭代 S3 对象,而不仅仅是对象中的所有键/存储桶

python - 使用 Python 检查文件是否为 CSV 格式

python - "Mark directory as sources root"到底是做什么的?

python - 无法在 matplotlib 中保存 920px 宽度的图形

python - 检查 for 循环变量是否驻留在列表的两个索引处

python - 如果未使用特定迭代器,类似 zip 的函数将失败

python - 在 python 列表中查找最小 float 的最有效方法