首页 > 解决方案 > 检查多个条件的最快方法

问题描述

我正在寻找 3 个条件,其中任何一个都会触发继续。

我正在查看的 2 种方法是 1) if 有多个条件 2) if 和 elif

def conditions_1(a,b,c):
    numbers = []
    min_no = min(a,b,c)
    max_no = max(a,b,c)
    for no in range(min_no,max_no+1):
        if no == 0 :
            continue
        elif no + min_no == 0:
            continue
        elif math.gcd(min_no, no)> 1:
            continue
        else:
            numbers.append(no)
    return(numbers)


def conditions_2(a,b,c):
    numbers = []
    min_no = min(a,b,c)
    max_no = max(a,b,c)
    for no in range(min_no,max_no+1):
        if no == 0 or no + min_no == 0 or math.gcd(min_no, no)> 1:
            continue
        else:
            numbers.append(no)
    return(numbers)

for _ in range(10):
    t0 = time.time()
    conditions_1(-5000, 10000, 4)
    t1 = time.time()
    conditions_2(-5000, 10000, 4)
    t2 = time.time()
    if t2-t1 > t1-t0:
        print('2nd')
    else:
        print('1st')

我可以知道这两种方式是否有区别吗?

标签: python

解决方案


由于or具有短路评估的事实(即,它评估从左到右的条件列表并在第一个 True 处停止),您的两个变体之间的执行模式是相同的(减去在 if/elif如果您在测试每个条件时可能会有多次跳转)。

就编码风格而言,第二个当然要好得多(没有重复continue,if/else 块的意图更清晰),并且应该是您构建代码的方式。

旁注:请记住,如果表达式太长,您可以将其放在括号中并将其分成几行:

if (some_very_lengthy_condition_1 == my_very_lengthy_name_1 or
    some_very_lengthy_condition_2 == my_very_lengthy_name_2 or
    some_very_lengthy_condition_3 == my_very_lengthy_name_3 ):
  pass # do something

正如 Gábor 在评论中指出的那样,在 python 中,您还有适用于可迭代对象的anyand运算符。等效于ing 迭代中的所有值,while等效于ing 它们。短路逻辑也适用于此处,因此在计算表达式结果时仅计算最小数量的值。allany(iterable)orall(iterable)anditerable


推荐阅读