This question already has an answer here:
这个问题在这里已有答案:
- python operator precedence of in and comparison 4 answers
- python运算符优先级in和比较4个答案
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!
方法1:此方法有效!
if not 9 in list: print "9 is not present in list"
Method 2: This method does not work.
方法2:此方法不起作用。
if 9 in list == False: print "9 is not present in list"
Can someone please explain why method 2 does not work?
有人可以解释为什么方法2不起作用?
2 个解决方案
#1
12
This is due to comparison operator chaining. From the documentation:
这是由于比较运算符链接。从文档:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).比较可以任意链接,例如,x
You are assuming that the 9 in list == False
expression is executed as (9 in list) == False
but that is not the case.
您假设列表中的9 = = False表达式执行为(列表中的9)== False,但事实并非如此。
Instead, python evaluates that as (9 in list) and (list == False)
instead, and the latter part is never True.
相反,python将其评估为(列表中的9)和(list == False),而后者则永远不是True。
You really want to use the not in
operator, and avoid naming your variables list
:
你真的想使用not in运算符,并避免命名你的变量列表:
if 9 not in lst:
#2
3
It should be:
它应该是:
if (9 in list) == False: print "9 is not present in list"
if(列表中的9)== False:打印“列表中不存在9”
#1
12
This is due to comparison operator chaining. From the documentation:
这是由于比较运算符链接。从文档:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).比较可以任意链接,例如,x
You are assuming that the 9 in list == False
expression is executed as (9 in list) == False
but that is not the case.
您假设列表中的9 = = False表达式执行为(列表中的9)== False,但事实并非如此。
Instead, python evaluates that as (9 in list) and (list == False)
instead, and the latter part is never True.
相反,python将其评估为(列表中的9)和(list == False),而后者则永远不是True。
You really want to use the not in
operator, and avoid naming your variables list
:
你真的想使用not in运算符,并避免命名你的变量列表:
if 9 not in lst:
#2
3
It should be:
它应该是:
if (9 in list) == False: print "9 is not present in list"
if(列表中的9)== False:打印“列表中不存在9”