逻辑与 (python) 的求值顺序

Order of evaluation of logical AND (python)

在python中效率更高的是:

if a:
    if b:
        # do something

if a and b:
    # do something

如果在 a 为 false 时不计算 b,则后者会更有效。但我似乎无法确定 Python 文档中是否属于这种情况。也许有人可以指点我一下?

这叫短路,is mentioned in the docs.

答案是,如果 a 为假,Python 将不会评估 b。

短路

如果 X 为假,

Python 不会在 X and Y 中 运行 Y。您可以自己尝试一下:

if True and print("Hello1"):
    pass

if False and print("Hello2"):
    pass # "Hello2" won't be printed

Python这样做的原因是它有一种叫做短路的东西可以优化像这样的逻辑表达式。 Python 意识到,如果 X 为假,那么检查 Y 就没有意义了,因为无论如何整个表达式都是假的。

如何避免短路

您可以在 Python 中使用逻辑运算符的按位版本绕过此问题:

and -> & 
or -> |

例如:

if True & bool(print("Hello1")):
    pass

if False & bool(print("Hello2")):
    pass # "Hello2" will be printed this time

但是请注意,您需要将 print 包装在 bool 中,因为按位仅适用于相同的数据类型。

性能

我认为只有一个 if 语句的性能会更快,否则 python 如果发现条件为真,可能必须经过 2 个 if 语句。

从左到右计算,简单实验

def iftrue1():
    print("iftrue1")
    return True

def iftrue2():
    print("iftrue2")
    return True

if iftrue1() and iftrue2():
    pass

这输出

iftrue1
iftrue2