Python 检查列表中是否不存在某个项目时,为什么此代码不起作用 - 如果列表中的项目 == False:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15336602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When checking if an item does not exist in a list, why doesn't this code work - if item in list == False:
提问by Raghav Mujumdar
Consider this list:
考虑这个列表:
list = [1,2,3,4,5]
I want to check if the number 9 is not present in this list. There are 2 ways to do this.
我想检查此列表中是否不存在数字 9。有两种方法可以做到这一点。
Method 1: This method works!
方法一:这个方法有效!
if not 9 in list: print "9 is not present in list"
Method 2: This method does not work.
方法二:此方法无效。
if 9 in list == False: print "9 is not present in list"
Can someone please explain why method 2 does not work?
有人可以解释为什么方法2不起作用吗?
采纳答案by Martijn Pieters
This is due to comparison operator chaining. From the documentation:
这是由于比较运算符链接。从文档:
Comparisons can be chained arbitrarily, e.g.,
x < y <= zis equivalent tox < y and y <= z, except thatyis evaluated only once (but in both caseszis not evaluated at all whenx < yis found to be false).
比较可以任意链接,例如,
x < y <= z等价于x < y and y <= z,除了y只计算一次(但在这两种情况下z,当x < y发现为假时根本不计算)。
You are assuming that the 9 in list == Falseexpression is executed as (9 in list) == Falsebut that is not the case.
您假设9 in list == False表达式执行为,(9 in list) == False但事实并非如此。
Instead, python evaluates that as (9 in list) and (list == False)instead, and the latter part is never True.
相反,python 将其评估为(9 in list) and (list == False)相反,而后一部分永远不会为 True。
You really want to use the not inoperator, and avoidnaming your variables list:
您确实想使用not in运算符,并避免命名变量list:
if 9 not in lst:
回答by Thanakron Tandavas
It should be:
它应该是:
if (9 in list) == False: print "9 is not present in list"
if (9 in list) == False: print "9 is not present in list"

