Home > Software design >  Multiply each element of a list by an entire other list
Multiply each element of a list by an entire other list

Time:08-09

I have two lists which are very large. The basic structure is : a = [1,0,0,0,1,1,0,0] and b=[1,0,1,0]. There is no restriction on the length of either list and there is also no restriction on the value of the elements in either list. I want to multiply each element of a by the contents of b. For example, the following code does the job:

multiplied = []
for a_bit in a:
     for b_bit in b:
          multiplied.append(a_bit*b_bit)

So for the even simpler case of a=[1,0] and b = [1,0,1,0], the output multiplied would be equal to:

>>> print(multiplied)
[1,0,1,0,0,0,0,0]

Is there a way with numpy or map or zip to do this? There are similar questions that are multiplying lists with lists and a bunch of other variations but I haven't seen this one. The problem is that, my nested for loops above are fine and they work but they take forever to process on larger arrays.

CodePudding user response:

You can do this using matrix multiplication, and then flattening the result.

>>> a = np.array([1,0]).reshape(-1,1)
>>> b = np.array([1,0,1,0])
>>> a*b
array([[1, 0, 1, 0],
       [0, 0, 0, 0]])
>>> (a*b).flatten()
array([1, 0, 1, 0, 0, 0, 0, 0])
>>>
  • Related