Home > OS >  how to subtract one list from another including duplicates
how to subtract one list from another including duplicates

Time:12-07

I have 2 lists

On is a big list with some elements having duplicates super_set_list = [1,1,2,3,3,4,4,4,5,6,7,8,9]

The other is a subset of the big list, also with duplicates sub_set_list = [1,2,3,3,4,4,6,7,9]

I want the difference, like this diff = [1,4,5,8]

Not sure how I would go about this

CodePudding user response:

You can use a Counter

super_set_list = [1,1,1,2,3,3,4,4,4,5,6,7,8,9]
sub_set_list = [1,2,3,3,4,4,6,7,9]

from collections import Counter
super_counter = Counter(super_set_list) 

super_counter = Counter({1: 3, 4: 3, 3: 2, 2: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})

For every element in sub_set_list, reduce the count in in super_counter

for item in sub_set_list:
    super_counter[item]-=1

Now super_counter = Counter({1: 2, 4: 1, 5: 1, 8: 1, 2: 0, 3: 0, 6: 0, 7: 0, 9: 0})

Finally, just pick elements that have some count left (but add it that many number of times).

diff=[]
for k,v in super_counter.items():
    for _ in range(v):
        diff.append(k)
print(diff)
# [1, 1, 4, 5, 8]

CodePudding user response:

You can loop through sub-set list and remove item in super-set list one by one as follows:

super_set_list = [1,1,2,3,3,4,4,4,5,6,7,8,9]
sub_set_list = [1,2,3,3,4,4,6,7,9]

for item in sub_set_list:
    if item in super_set_list:
        super_set_list.remove(item)
print(super_set_list)
  • Related