简体   繁体   English

逻辑AND的评估顺序(python)

[英]Order of evaluation of logical AND (python)

In python, which is more efficient: 在python中,效率更高:

if a:
    if b:
        # do something

or 要么

if a and b:
    # do something

The latter would be more efficient if b isn't calculated when a is false. 如果在a为假时不计算b则后者会更有效。 But I can't seem to pinpoint whether that's the case in Python docs. 但是我似乎无法查明Python文档是否属于这种情况。 Maybe someone can point me to it? 也许有人可以指出我的意思?

Short-Circuiting 短路

Python doesn't run Y in X and Y if X is false. Python不会在X and Y运行Y ,如果X为false X and Y不会运行Y You can try it out yourself: 您可以自己尝试:

if True and print("Hello1"):
    pass

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

The reason Python does this is it has something called short-circuiting which optimising logic expressions like this one. Python之所以这样做是因为它具有一种称为短路的功能,可以优化像这样的逻辑表达式。 Python realises that if if X is false then there is no point in checking Y because the whole expression will be false anyway. Python意识到,如果X为假,则检查Y是没有意义的,因为整个表达式仍然为假。

How to Avoid Short-Circuiting 如何避免短路

You can bypass this in Python by using the bitwise versions of the logic operators: 您可以使用逻辑运算符的按位版本在Python中绕过此操作:

and -> & 
or -> |

For example: 例如:

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

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

Note however that you need to wrap print in bool because bitwise only works on the same data types. 但是请注意,您需要将print包装在bool因为按位仅适用于相同的数据类型。

Performance 性能

I would imagine performance wise the one with only one if statement would be faster as other wise python might have to go through 2 if statements if it finds the conditions are true. 我可以想象性能明智的一个if语句将更快,因为其他明智的python如果发现条件为true则可能必须经过2 if语句。

This is called short-circuiting, and it is mentioned in the docs . 这称为短路,并在docs中提到

And the answer is, Python will not evaluate b if a is False. 答案是,如果a为False,Python将不会评估b。

It evaluates from left to right, simple experiment 它从左到右进行评估,简单的实验

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

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

if iftrue1() and iftrue2():
    pass

This outputs 这个输出

iftrue1
iftrue2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM