Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lists to return a list with all elements as 0 except the ones which matched while keeping index?

I am a bit stuck on this:

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

I want to compare the two lists and generate a list with the same items as a, but with any items that don't occur in b set to 0. Valid outputs would be these:

c = [0,2,0,0,0,5]
# or
c = [0,0,0,2,0,5]

I would not know the number elements in either list beforehand.

I tried for loops but

['0' for x in a if x not in b]

It removes all instances of 2. Which I only want to remove once(it occurs once in b for the moment). I need to add a condition in the above loop to keep elements which match.

like image 617
Sid Avatar asked Jan 28 '26 19:01

Sid


2 Answers

The following would work:

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

output = []

for x in a:
    if x in b:
        b.remove(x)
        output.append(x)
    else:
        output.append(0)

or for a one-liner, using the fact that b.remove(x) returns None:

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

output = [(b.remove(x) or x) if x in b else 0 for x in a]
like image 98
Jacques Gaudin Avatar answered Jan 30 '26 09:01

Jacques Gaudin


If the elements in b are unique, this is best done with a set, because sets allow very efficient membership testing:

a = [1,2,3,2,4,5]
b = {2, 5}  # make this a set

result = []
for num in a:
    # If this number occurs in b, remove it from b.
    # Otherwise, append a 0.
    if num in b:
        b.remove(num)
        result.append(num)
    else:
        result.append(0)

# result: [0, 2, 0, 0, 0, 5]

If b can contain duplicates, you can replace the set with a Counter, which represents a multiset:

import collections

a = [1,2,3,2,4,5]
b = collections.Counter([2, 2, 5])

result = []
for num in a:
    if b[num] > 0:
        b[num] -= 1
        result.append(num)
    else:
        result.append(0)

# result: [0, 2, 0, 2, 0, 5]
like image 38
Aran-Fey Avatar answered Jan 30 '26 08:01

Aran-Fey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!