これらのリストで:
a=[2,6,79,10]
b=[6,7,2,0,8,5]
必要な出力は次のとおりです。
a=[79,10]
b=[7,0,8,5]
このコードが機能しないのはなぜですか?
def cel(a,b):
for x in a:
if x in b:
b.remove(x)
a.remove(x)
これらのリストで:
a=[2,6,79,10]
b=[6,7,2,0,8,5]
必要な出力は次のとおりです。
a=[79,10]
b=[7,0,8,5]
このコードが機能しないのはなぜですか?
def cel(a,b):
for x in a:
if x in b:
b.remove(x)
a.remove(x)
この目的でset操作を使用できます。
i = set(a).intersection(set(b))
a = list(set(a).difference(i))
b = list(set(b).difference(i))
編集私はあなたの元のコードをデバッグしようとしました、そしてそれが1つを削除するときはいつでもそれが数をスキップすることに気づきました。グーグルした後、いくつかの内部インデックスの問題のために、反復中にリストを変更することは定義された動作ではないことがわかりました。最も簡単な回避策は、forループで元の配列のコピーを次のように使用することです。
for x in a[:]:
if x in b:
b.remove(x)
a.remove(x)
順序を保持する@gokcehanの回答のアルゴリズムは3次O(n**3)
です。中程度のサイズのリストでも非常に非効率的です(Programming Pearlsの本には、Basicの線形アルゴリズムがCの3次アルゴリズム(分対日)よりも優れている例があります)。
順序を保持し、線形時間で実行できます。
common = set(a).intersection(b)
a = [x for x in a if x not in common]
b = [x for x in b if x not in common]
あなたはそれをその場で行うことができます:
def remove_items(lst, items):
items = set(items) # unnecessary in your case
pos = 0
for x in lst:
if x not in items:
lst[pos] = x # save
pos += 1
del lst[pos:]
common = set(a).intersection(b)
remove_items(a, common)
remove_items(b, common)