目标是在两个列表中找到共同元素,同时保留重复项。
例如
输入:
a = [1,3,3,4,5,5]
b = [3,5,5,5,6]
预期输出:
[3,5,5]
我试过 set.intersection
但集合操作会消除重复项。
答案 0 :(得分:3)
这是我的建议:
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]
答案 1 :(得分:2)
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]
可能有用。
答案 2 :(得分:2)
您可以使用列表的计数器,并使用那些同时出现在它们的值中的键和最少数量的值:
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]
答案 3 :(得分:2)
使用 Counter
模块中的 collections
。
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]
答案 4 :(得分:1)
答案取决于列表是否总是像您的示例中那样排序。如果是这样,您可以使用游标方法 where
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))
?
答案 5 :(得分:1)
保留重复项让我很头疼,但最终找到了解决方案
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
答案 6 :(得分:0)
试试这个。您可以使用 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)
答案 7 :(得分:-3)
尽管 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]
应该可以