我有两个正整数排序列表,它们可以有重复元素,我必须从每个列表中删除匹配的数字对:
a=[1,2,2,2,3]
b=[2,3,4,5,5]
should become:
a=[1,2,2]
b=[4,5,5]
也就是说,2和3已经被删除了,因为它们在两个列表中都出现了。
由于有重复元素,无法使用集合交集。
我该怎么做?
我有两个正整数排序列表,它们可以有重复元素,我必须从每个列表中删除匹配的数字对:
a=[1,2,2,2,3]
b=[2,3,4,5,5]
should become:
a=[1,2,2]
b=[4,5,5]
也就是说,2和3已经被删除了,因为它们在两个列表中都出现了。
由于有重复元素,无法使用集合交集。
我该怎么做?
for i in a[:]:
if i in b:
a.remove(i)
b.remove(i)
要创建此函数,请执行以下操作:
```def removeCommonElements(a, b):
for e in a[:]:
if e in b:
a.remove(e)
b.remove(e)
def getWithoutCommonElements(a, b): # Name subject to change
a2 = a.copy()
b2 = b.copy()
for e in a:
if e not in b:
a2.remove(e)
b2.remove(e)
return a2, b2
removeCommonElements
,方法如下:a2, b2 = a.copy(), b.copy()
removeCommonElements(a2, b2)
a=[1,2,2,2,3]
和 b=[2,2,3,4,5]
不起作用,它会使 a=[1,2,3]
,b=[3,4,5]
。 - nrusselliter(a)
替换为 a[:]
即可解决问题。 - pemistahl从collections中的Counter对象可以非常简洁地实现此操作:
from collections import Counter
a=Counter([1,2,2,2,3])
b=Counter([2,3,4,5,5])
print list((a-b).elements())
print list((b-a).elements())
x, y = [], []
while a and b:
if a[0] < b[0]:
x.append(a.pop(0))
elif a[0] > b[0]:
y.append(b.pop(0))
else: # a[0]==b[0]
a.pop(0)
b.pop(0)
x += a
y += b
def remove_common_elements(a, b):
for i in a[:]:
if i in b:
a.remove(i)
b.remove(i)
return a, b
a [:]
来复制 a
。如果您在从列表中删除元素时迭代该列表,则不会获得正确的结果。def remove_common_elements(a, b):
a_new = a[:]
b_new = b[:]
for i in a:
if i in b_new:
a_new.remove(i)
b_new.remove(i)
return a_new, b_new
a = [1,2,2,2,3]
b = [2,2,3,4,5]
a_new = []
for ai in a:
if ai in b:
b.remove(ai)
else:
a_new.append(ai)
print a_new
print b