How to perform element-wise multiplication of two lists?
I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.
This is how I would do it in Matlab.
a = [1,2,3,4] b = [2,3,4,5] a .* b = [2, 6, 12, 20]
A list comprehension would give 16 list entries, for every combination
x * y of
b. Unsure of how to map this.
If anyone is interested why, I have a dataset, and want to multiply it by
Numpy.linspace(1.0, 0.5, num=len(dataset)) =).
Use a list comprehension mixed with
[a*b for a,b in zip(lista,listb)]
Since you're already using
numpy, it makes sense to store your data in a
numpy array rather than a list. Once you do this, you get things like element-wise products for free:
In : import numpy as np In : a = np.array([1,2,3,4]) In : b = np.array([2,3,4,5]) In : a * b Out: array([ 2, 6, 12, 20])
Read more... Read less...
import numpy as np a = [1,2,3,4] b = [2,3,4,5] np.multiply(a,b)
You can try multiplying each element in a loop. The short hand for doing that is
ab = [a[i]*b[i] for i in range(len(a))]
Yet another answer:
-1 ... requires import
+1 ... is very readable
import operator a = [1,2,3,4] b = [10,11,12,13] list(map(operator.mul, a, b))
outputs [10, 22, 36, 52]
Fairly intuitive way of doing this:
a = [1,2,3,4] b = [2,3,4,5] ab =  #Create empty list for i in range(0, len(a)): ab.append(a[i]*b[i]) #Adds each element to the list
you can multiplication using
foo=[1,2,3,4] bar=[1,2,5,55] l=map(lambda x,y:x*y,foo,bar)