Python:如何将布尔测试链接到第一个False后立即获取False

hel*_*ker 0 python boolean short-circuiting truthtable

在尝试减少嵌套ifs(以及停止工作的脚本)之后遇到了很多麻烦,我意识到我可能错误地了解boolean stuff在python中的作用和方式.

我有这个(工作正常,但扭曲):

if (not gotside):
    if (j > 1):
        if (j < a.shape[1] - 1):
            if a[i, j+unit]:
                print "only now I do stuff!"
Run Code Online (Sandbox Code Playgroud)

并尝试了这一点(看起来因为没有按预期工作而感到惊讶):

if (not gotside) and (j > 1) and (j < a.shape[1] - 1) and a[i, j+unit]:
    print "I'm well tested but not so indented..."
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用"或"而不是"和",但没有工作,因为(后来我发现)当你使用x and y,甚至x or y你得到一个x, y,而不是一个True, False,根据文档.

所以,我不知道如何能够以一种方式一个接一个地放置一些测试(最好是在同一行中,使用布尔运算符),False一旦第一个测试计算为False ,整个表达式就会返回.

谢谢阅读!

Gar*_*tty 6

你的例子应该有效.

if x and y and z:
    ...
Run Code Online (Sandbox Code Playgroud)

只有当x,y和z都没有评估时才会发生False,并且在Python中and发生短路,所以False只要一个项目失败就会返回值.我们可以很容易地证明这一点:

>>> def test(n):
...     print("test", n)
...     return n
... 
>>> test(1) and test(2)
test 1
test 2
2
>>> test(0) and test(2)
test 0
0
>>> test(0) and test(2) and test(3)
test 0
0
>>> test(1) and test(0) and test(3)
test 1
test 0
0
Run Code Online (Sandbox Code Playgroud)