Element-wise boolean multiplication

  • A+
Category:Languages

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

 


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()

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: