简体   繁体   English

Python:为什么“ [1,2,3]中的2 == True”返回False?

[英]Python: Why “2 in [1,2,3] == True” returns False?

Suppose I enter this in Shell, then I get True . 假设我在Shell中输入了代码,则得到True。

>>>ar=[2,4,6,8]
>>>2 in ar
True

But when I try to use this, it doesn't work 但是当我尝试使用它时,它不起作用

>>>if 2 in ar==True:
       print("YES")

>>> 
>>> 

It doesn't work! 它不起作用! The if condition is False. 如果条件为False。 What can I do to check whether a term is there in a list with a loop? 如何检查带有循环的列表中是否存在术语? For example: I am given some random list and I have to print all the even numbers present in the list? 例如:给我一些随机列表,我是否必须打印列表中出现的所有偶数?

That is because with comparison operators, x operator1 y operator2 z is equivalent to (x operator1 y) and (y operator2 z) except that y is evaluated only once. 这是因为使用比较运算符, x operator1 y operator2 z等于(x operator1 y) and (y operator2 z)除了y仅被评估一次。 Therefore 2 in ar == True is equivalent to (2 in ar) and (ar == True) . 因此2 in ar == True等效于(2 in ar) and (ar == True) ar == True is False, so the if block is not executed. ar == True为False,因此不会执行if块。 Just put parentheses around 2 in ar : if (2 in ar) == True: You really don't need the == True , though. 只需2 in ar中的2 in ar周围加上括号: if (2 in ar) == True:您实际上并不需要== True Just do if 2 in ar: . 只要if 2 in ar:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM