Python efficiency of and vs multiple ifs

后端 未结 5 866
太阳男子
太阳男子 2021-02-07 05:32

Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like

if expr1 == expr2 and         


        
5条回答
  •  孤街浪徒
    2021-02-07 06:07

    Any differences in speed between using and and nested ifs will be minimal. You are barking up the wrong tree. Consider this tree:

    if oftenTrueCondition and rarelyTrueCondition:
    

    compared with

    if rarelyTrueCondition and oftenTrueCondition:
    

    So, unless the first condition must be evaluated first (it is a guard to stop the next expression from crashing or doing something silly/expensive), consider swapping the order of evaluation.

提交回复
热议问题