[英]Difference Between Two Lists with Duplicates in Python
我有兩個列表,其中包含許多相同的項目,包括重復的項目。 我想檢查第一個列表中的哪些項目不在第二個列表中。 例如,我可能有一個這樣的列表:
l1 = ['a', 'b', 'c', 'b', 'c']
和一個這樣的列表:
l2 = ['a', 'b', 'c', 'b']
比較這兩個列表,我想返回這樣的第三個列表:
l3 = ['c']
我目前正在使用我不久前編寫的一些糟糕的代碼,我相當肯定它甚至不能正常工作,如下所示。
def list_difference(l1,l2):
for i in range(0, len(l1)):
for j in range(0, len(l2)):
if l1[i] == l1[j]:
l1[i] = 'damn'
l2[j] = 'damn'
l3 = []
for item in l1:
if item!='damn':
l3.append(item)
return l3
我怎樣才能更好地完成這項任務?
您沒有說明訂單是否重要。 如果沒有,您可以在 >= Python 2.7 中執行此操作:
l1 = ['a', 'b', 'c', 'b', 'c']
l2 = ['a', 'b', 'c', 'b']
from collections import Counter
c1 = Counter(l1)
c2 = Counter(l2)
diff = c1-c2
print list(diff.elements())
為兩個列表創建Counter ,然后subtract
另一個列表中subtract
一個。
from collections import Counter
a = [1,2,3,1,2]
b = [1,2,3,1]
c = Counter(a)
c.subtract(Counter(b))
要同時考慮重復項和元素的順序:
from collections import Counter
def list_difference(a, b):
count = Counter(a) # count items in a
count.subtract(b) # subtract items that are in b
diff = []
for x in a:
if count[x] > 0:
count[x] -= 1
diff.append(x)
return diff
print(list_difference("z y z x v x y x u".split(), "x y z w z".split()))
# -> ['y', 'x', 'v', 'x', 'u']
Python 2.5 版本:
from collections import defaultdict
def list_difference25(a, b):
# count items in a
count = defaultdict(int) # item -> number of occurrences
for x in a:
count[x] += 1
# subtract items that are in b
for x in b:
count[x] -= 1
diff = []
for x in a:
if count[x] > 0:
count[x] -= 1
diff.append(x)
return diff
計數器是 Python 2.7 中的新功能。 對於從 b 中減去 a 的一般解決方案:
def list_difference(b, a):
c = list(b)
for item in a:
try:
c.remove(item)
except ValueError:
pass #or maybe you want to keep a values here
return c
你可以試試這個
list(filter(lambda x:l1.remove(x),li2)) print(l1)
試試這個:
from collections import Counter
from typing import Sequence
def duplicates_difference(a: Sequence, b: Sequence) -> Counter:
"""
>>> duplicates_difference([1,2],[1,2,2,3])
Counter({2: 1, 3: 1})
"""
shorter, longer = sorted([a, b], key=len)
return Counter(longer) - Counter(shorter)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.