Ahs*_*eem 3 python boolean-logic list 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"
Run Code Online (Sandbox Code Playgroud)
输出:
not true
Run Code Online (Sandbox Code Playgroud)
当我这样做:
a= ["john", "carlos", "22", "70"]
if ("qjohn" or "cdarlos" in a) and ("272" or "d70" in a):
print "true"
else:
print "not true"
Run Code Online (Sandbox Code Playgroud)
输出是 "true"
我没有得到的**carlos and 70**应该是真实的,但它打印"不真实".这个错误的原因是什么?谢谢
两种方法都不正确.请记住或者是短路操作员,因此它不会按照您的想法执行操作:
如果第一个参数为false,它只计算第二个参数.
但是,非空字符串总是True如此,因此第一种情况只检查第一个非空字符串的包含,而第二种情况从不执行包含检查in,因此,它始终是True.
你想要的是:
if ("qjohn" in a or "carlos" in a) and ("272" in a or "70" in a):
...
Run Code Online (Sandbox Code Playgroud)
如果要测试的项目更长,您可以避免重复or使用any哪些项目or也会在其中一项项目测试时发生短路True:
if any(x in a for x in case1) and any(x in a for x in case2):
...
Run Code Online (Sandbox Code Playgroud)