Home > Blockchain >  Subtract as many likes from a list in Python
Subtract as many likes from a list in Python

Time:12-30

a=[["a","a"], ["a", "a"], ["b","b"], ["b","b"], ["c", "c", "c"]]

b=[["b","b"], ["a", "a"]]

the code should output something like

new_list=[["a", "a"], ["b","b"], ["c", "c", "c"]]

because this is what remains when we subtract b from a.

when I tried, usually the same ones were deleted completely.

CodePudding user response:

So I'm gonna guess you tried something like

for element in a:
    if element in b:
        a.remove(element)

This has the problem that it will remove every single copy from a if it is found in b. Instead, you want to iterate over the elements in b so you only remove them once (or rather, however often they appear in b):

for element in b:
    if element in a:
        a.remove(element)

For the future: Please always include the code you have tried.

CodePudding user response:

I tried @yagod's answer, but there is a problem: after removing an item, jumps over the next item (you need to remove the item from b to, and go back to the previous element):

i = 0
while i < len(a):
    try:
        del b[b.index(a[i])]
        del a[i]
        i -= 1
    except ValueError:
        # If a[i] not in b
        pass
    i  = 1

@yagod, your code doesn't pass for example this test:

a=[["a","a"], ["a", "a"], ["a", "a"], ["b","b"], ["b","b"], ["c", "c", "c"]]
b=[["b","b"], ["a", "a"]]

With your code: [['a', 'a'], ['b', 'b'], ['c', 'c', 'c']]

Correct solution: [['a', 'a'], ['a', 'a'], ['b', 'b'], ['c', 'c', 'c']]

  • Related