簡體   English   中英

檢查多個條件的最快方法

[英]Fastest way to check for multiple conditions

我正在尋找 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')

我可以知道這兩種方式是否有區別嗎?

由於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 中,您還擁有適用於可迭代對象的anyall運算符。 any(iterable)等價於or ing iterable 中的所有值,而all(iterable)等價於and ing 它們。 短路邏輯也適用於此,因此在計算表達式結果時,只計算iterable的最小數量的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM