Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise boolean multiplication

Tags:

python

numpy

I'm looking for the most beautiful and short way to multiply those types of lists:

a = [True, False, True, False, False]

b = [100, 200]

Length of b equals to number of True elements in a

The answer that I need is [100, 0, 200, 0, 0] here

Are there any simple ways to get that answer?
It looks like element-wise multiplication, but the fact is that the size of the second list is smaller, so common numpy methods don't work without bad code.

Hope, you'll find nice solution

like image 649
John Makkonen Avatar asked Nov 30 '22 14:11

John Makkonen


2 Answers

You could do this in numpy:

c = np.array(a).astype(int)

c[c==1] = b

>>> c
array([100,   0, 200,   0,   0])

Note If you need the result as a list (based on your desired output), rather than a numpy array, use c.tolist()

like image 198
sacuL Avatar answered Dec 03 '22 04:12

sacuL


There's a pretty clean iterator based solution

it = iter(b)
[next(it) if x else 0 for x in a]
# [100, 0, 200, 0, 0]
like image 24
Patrick Haugh Avatar answered Dec 03 '22 03:12

Patrick Haugh