Delete common items in two lists

I have two sorted lists of positive integers that can have repeating elements, and I have to remove the corresponding pairs of numbers, one from each list:

a=[1,2,2,2,3] b=[2,3,4,5,5] 

should become:

 a=[1,2,2] b=[4,5,5] 

That is, 2 and 3 were deleted because they appear in both lists.

Intersection cannot be used here due to duplicate elements.

How can I do it?

+4
source share
5 answers

To remove items displayed in both lists, use the following:

 for i in a[:]: if i in b: a.remove(i) b.remove(i) 

To create a function that does this for you, simply do:

 def removeCommonElements(a, b): for e in a[:]: if e in b: a.remove(e) b.remove(e) 

Or return new lists, rather than edit old ones:

 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 

However, the former can be replaced with removeCommonElements as follows:

 a2, b2 = a.copy(), b.copy() removeCommonElements(a2, b2) 

To save a and b, but to create duplicates without common elements.

+3
source

The Counter object from collections can do this briefly enough:

 from collections import Counter a=Counter([1,2,2,2,3]) b=Counter([2,3,4,5,5]) print list((ab).elements()) print list((ba).elements()) 

The idea is this:

  • Count how often each item appears (e.g. 2 appears 3 times in and 1 time in b)
  • Subtract the calculations to determine the number of extra times the element appears (for example, 2 appears 3-1 = 2 times more compared to b)
  • Print each item an additional number of times (the collection item method automatically deletes any items with an amount less than 1)

(Warning: output lists will not necessarily be sorted)

+2
source

Given that the lists are sorted, you can combine / distribute by elements, for example, for example:

 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 
+2
source

The solution given by @Mahi is almost correct. The easiest way to achieve what you want is:

 def remove_common_elements(a, b): for i in a[:]: if i in b: a.remove(i) b.remove(i) return a, b 

It is important here to make a copy of a by writing a[:] . If you iterate over a list by removing items from it, you will not get the correct results.

If you do not want to modify the lists in place, make a copy of both lists in advance and return the copied lists.

 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 
+1
source

One solution would be to create a new copy of a and remove the common elements from b.

 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 
0
source

All Articles