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()
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With