簡體   English   中英

python在比較項目時迭代兩個列表

[英]python iterate over the two lists while comparing items

我有兩個列表,例如x = [1,2,3,4,4,5,6,7,7] y = [3,4,5,6,7,8,9,10] ,我想迭代比較項目時在兩個列表上。 對於那些匹配,我想調用一些函數並從列表中刪除它們,在這個例子中我應該最終得到x = [1,2]和y = [8,9,10]。 由於我的數據類型和比較運算符,集合不適用於此問題。

for i in x:
  for j in y:
    if i ==j:
       callsomefunction(i,j)
       remove i, j from x and y respectively

編輯:在發現提問的人根本不知道__hash__我在評論中提供了這些信息:

要使用集合,請實現__hash__ 因此,如果obj1 == obj2obj1.a == obj2.a and ob1.b == obj2.b__hash__應該return hash((self.a, self.b)) ,你的集合將按預期工作。

這解決了他們的問題,他們轉而使用套裝。

這個答案的其余部分現在已經過時了,但它仍然是正確的(但效率非常低)所以我會把它留在這里。


這段代碼可以滿足您的需求。 最后, newxnewyxy的非重疊項目。

x = [1,2,3,4,4,5,6,7,7]
y = [3,4,5,6,7,8,9,10]
# you can leave out bad and just compare against
# x at the end if memory is more important than speed
newx, bad, newy = [], [], []
for i in x:
    if i in y:
        callsomefunction(i)
        bad.append(i)
    else:
        newx.append(i)

for i in y:
    if i not in bad:
        newy.append(i)

print newx
print newy

但是,我知道甚至沒有看到你的代碼,這是錯誤的方法來做到這一點。 你當然可以用套裝做,但如果你不想,那取決於你。

好的,丟棄我的帖子,我沒有看到你提到的那些設置不起作用。

然而,如果你可以做一點工作,你可能想要使用類,以便運算符按照預期的那樣工作

我認為最“蟒蛇式”的做法是使用套裝。 然后你可以這樣做:

x = set([1,2,3,4,4,5,6,7,7])
y = set([3,4,5,6,7,8,9,10])
for item in x.intersection(y): #y.intersection(x) is fine too.
    my_function(item) #You could use my_function(item, item) if that's what your function requires
    x.remove(item)
    y.remove(item)

我認為,當涉及到性能時,這些集合也比這類工作的列表更有效(盡管這可能不是您的首要任務)。

在旁注中,您還可以使用:

x,y = x.difference(y), y.difference(x) 

這有效地從x和y中移除x和y中的項目。

嘗試這個:

for i in x:
    if i in y:
        callsomefunction(i)
        x.remove(i)
        y.remove(i)

編輯:更新的答案

這個怎么樣:

import itertools
x = [1,2,3,4,4,5,6,7,7] 
y = [3,4,5,6,7,8,9,10]
output = map(somefunction, itertools.product(x,y))

暫無
暫無

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

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