Python 嵌套的;和/或;如果语句
我正在编写代码,该代码创建一个列表,然后应用“或”和“和”条件来执行进一步的操作:Python 嵌套的;和/或;如果语句,python,list,boolean-logic,nested-if,Python,List,Boolean Logic,Nested If,我正在编写代码,该代码创建一个列表,然后应用“或”和“和”条件来执行进一步的操作: 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"
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"
输出为“真”
我没有得到的是,
**carlos和70**
应该等于true,但它打印的是“nottrue”。这个错误的原因是什么?谢谢这两种方法都不正确。请记住,或是一个短路操作员,因此它不会做您认为它会做的事情:
只有当第一个参数为false时,它才会计算第二个参数
但是,非空字符串始终为True
,因此第一种情况仅检查第一个非空字符串的包含,而第二种情况根本不使用中的执行包含检查,因此,它始终为True
你想要的是:
if ("qjohn" in a or "carlos" in a) and ("272" in a or "70" in a):
...
如果要测试的项目较长,您可以通过使用任何类似或的来避免重复或,也可以在其中一个项目测试为真时短路:
if any(x in a for x in case1) and any(x in a for x in case2):
...
如果集合的交集导致一个非空集合(成员测试),则条件为True
——在这方面,测试非空集合的真实性是一种很好的方法
或者,使用set.intersection
:
if {"qjohn", "carlos"}.insersection(a) and {"272", "70"}.insersection(a):
....
两者都是错误的。你理解的逻辑是错误的
a
中的(“qjohn”或“carlos”)相当于a
中的“qjohn”
及
“qjohn”或“cdarlos”在a
中相当于“qjohn”或(“cdarlos”在a)
可能很有用:不太重复,但处理相同的基本问题:如果使用交集
方法,则无需预计算集合b
;该方法可以将任何iterable作为其参数<代码>{“qjohn”,“carlos”}。交叉点(a)
,等等。(你是否想这样做取决于a
的大小。)@chepner谢谢。我认为这是一个被低估的解决方案。
if {"qjohn", "carlos"}.insersection(a) and {"272", "70"}.insersection(a):
....