簡體   English   中英

在Python中高效地遍歷列表

[英]Efficiently looping through lists in Python

我需要制作一個python函數,給定有序列表ab如果b存在一個項目,並且認為b中存在a+1a+1的項目,則返回True

當然,可以使用以下方法輕松完成此操作:

for item in a:
  if (a+1 in b):
     return True

但是,我需要使其盡可能高效,因為該函數將用於處理數據加載。 給我的提示是使用iter()next()操作,但是我還沒有找到一種將它們用於有效處理的方法。 有誰知道如何實現這些,或使用另一個快速算法? 提前致謝。

我可以看到兩個更有效的選擇。

  1. 通過在每個元素去a ,並執行二進制搜索element+1b

時間復雜度:O(n * log(m))其中n = |a| 和m = |b|

    for element in a:
        if binary_search(a, element+1):
            return True
    return False
  1. 通過[0, |a|增加兩個計數器 )和[0, |b| ),說ij i小於|a|循環 並且j小於|b| a[i] + 1b[j] 如果它們相等,則返回True 如果a[i] + 1 > b[j] ,則遞增j 否則,增加i

時間復雜度:O(n + m)其中n = |a| 和m = |b|

    i = 0
    j = 0
    while i < len(a) and j < len(b):
        if a[i] + 1 == b[j]:
            return True
        elif a[i] + 1 > b[j]:
            j += 1
        else:
            i += 1
    return False            

警告:代碼測試得不好。 假設您編寫了排序列表。

使用iternext提示的背后的想法是,在一個循環中,您可以在一個列表中或另一個列表中前進。 如果第一個數字太小,請嘗試下一個第一個數字。 如果第二個數字太小,請嘗試輸入第二個數字。

def test1(a, b): 
    ia = iter(a)
    ib = iter(b)
    try:
        ea = next(ia)
        eb = next(ib)
        while True:
            print("debug: comparing {} -- {}".format(ea, eb))
            diff = ea - eb
            if diff == -1: 
                print("debug: OK!")
                return True
            elif diff < -1: 
                ea = next(ia)
            else:
                eb = next(ib)
    except StopIteration:
        print("debug: not found")
        return False

lista=[1,2,4,10,31,33,45,67]
listb=[7,16,22,29,34,39,49,59,60,100,200,300]
test1(lista, listb)

輸出顯示了正在使用的算法:

debug: comparing 1 -- 7
debug: comparing 2 -- 7
debug: comparing 4 -- 7
debug: comparing 10 -- 7
debug: comparing 10 -- 16
debug: comparing 31 -- 16
debug: comparing 31 -- 22
debug: comparing 31 -- 29
debug: comparing 31 -- 34
debug: comparing 33 -- 34
debug: OK!

謝謝你們的回答! 我最終使用了您的解決方案的組合版本:

a = iter(l1)
b = iter(l2)
i = next(a)
j = next(b)
try:
    while (i):
        if i + 1 == j:
            return True
        elif i + 1 > j:
            j = next(b)
        else:
            i = next(a)
except StopIteration:
    return False

暫無
暫無

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

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