![](/img/trans.png)
[英]Common elements between two lists and preserving the order of elements in the two lists
[英]Common elements in two lists preserving duplicates
目標是在兩個列表中找到公共元素,同時保留重復項。
例如,
輸入:
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
預期輸出:
[3,5,5]
我試過set.intersection
但設置操作會消除重復項。
這是我的建議:
from collections import Counter
ac=Counter(a)
bc=Counter(b)
res=[]
for i in set(a).intersection(set(b)):
res.extend([i] * min(bc[i], ac[i]))
>>> print(res)
[3, 5, 5]
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
def findout(a, b):
a = a.copy()
output = []
for i in b:
if i in a:
a.remove(i)
output.append(i)
return output
result = findout(a, b)
print(result) # [3, 5, 5]
可能工作。
您可以使用列表的 Counter 並使用那些出現在它們的值中的鍵和最小數量的鍵:
from collections import Counter
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
ca = Counter(a)
cb = Counter(b)
result = [a for b in ([key] * min(ca[key], cb[key])
for key in ca
if key in cb) for a in b]
print(result)
輸出:
[3,5,5]
使用collections
模塊中的Counter
。
from collections import Counter
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
ans = []
a_count = Counter(a)
b_count = Counter(b)
for i in a_count:
if i in b_count:
ans.extend([i]*min(a_count[i], b_count[i]))
print(ans)
輸出
[3, 5, 5]
答案取決於列表是否總是像您的示例中那樣排序。 如果是這樣,您可以在其中執行游標方法
index_a = 0
index_b = 0
common_elements = []
while index_a < len(a) and index_b < len(b):
if a[index_a] < b[index_b]:
# then a should check the next number, b should stay
index_a += 1
elif a[index_a] > b[index_b]:
# then the reverse
index_b += 1
else:
# they are equal
common_elements.append(a[index_a])
index_a += 1
index_b += 1
但是,如果它們不是這樣排序的,您最好先進行集合交集,然后將其轉回列表,然后為每個元素添加重復項以等於min(a.count(el), b.count(el))
?
保留重復項引起了我的注意,但最終得到了解決方案
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
c=[]
def dublicate_finder(a,b):
global c
if len(a)>len(b):
for i in range(len(b)):
if b[i] in a:
c.append(b[i])
remove_index=a.index(b[i],0,len(a))
del a[remove_index]
if len(a)>len(b):
for i in range(len(a)):
if a[i] in b:
c.append(a[i])
remove_index=b.index(a[i],0,len(b))
del a[remove_index]
return c
試試這個。 您可以使用any
運算符來檢查元素是否等於其他列表中的元素。
然后刪除元素
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
l3=[]
for i in b:
if any(i==j for j in a):
l3.append(i)
a.remove(i)
print(l3)
盡管set.intersection
刪除了重復項,但它仍然非常有用:
a_set = set(a)
b_set = set(b)
intr = a_set.intersection(set_b)
result = [element for element in a if element in intr]
那應該工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.