嵌套的“和/或"如果陈述 [英] nested "and/or" if statements
问题描述
我正在研究创建列表的代码,然后同时应用或"和与"条件来执行进一步的操作:
I am working on code which creates a list and then applies both the "or" and "and" conditions to do further action:
a= ["john", "carlos", "22", "70"]
if (("qjohn" or "carlos") in a) and (("272" or "70") in a):
print "true"
else:
print "not true"
输出:
not true
当我这样做时:
a= ["john", "carlos", "22", "70"]
if ("qjohn" or "cdarlos" in a) and ("272" or "d70" in a):
print "true"
else:
print "not true"
输出为"true"
我没有得到的是**carlos and 70**
应该等于true,但是它打印的是"not true".此错误的原因是什么?谢谢
What I am not getting is **carlos and 70**
should be equal to true but it's printing "not true". What is the cause of this error? Thanks
推荐答案
两种方法都不正确.请记住,或是短路运算符,因此它没有按照您的预期做:
Both approaches are incorrect. Keep in mind or is a short-circuit operator so it's not doing what you think it does:
仅在第一个参数为false时才评估第二个参数.
it only evaluates the second argument if the first one is false.
但是,非空字符串始终为True
,因此第一种情况仅检查第一个非空字符串的包含,而第二种情况根本不使用in
进行容纳检查,因此,它始终为True
.
However, non-empty strings are always True
, so that the first case only checks for the containment of the first non-empty string while the second never performs the containment check with in
at all, therefore, it is always True
.
您想要的是:
if ("qjohn" in a or "carlos" in a) and ("272" in a or "70" in a):
...
如果要测试的项目较长,则可以使用any
避免重复or
,就像or
一样,一旦其中一项测试True
也会短路:
If the items to test were longer, you could avoid repeating the or
by using any
which like or
also short-circuits once one of the items test True
:
if any(x in a for x in case1) and any(x in a for x in case2):
...
这篇关于嵌套的“和/或"如果陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!