What is the neatest way to multiply element-wise a list of lists of numbers?
E.g.
[[1,2,3],[2,3,4],[3,4,5]]
-> [6,24,60]
Multiply two lists using for loop We can simply get the product of two lists using for loop. Through for loop, we can iterate through the list. Similarly, with every iteration, we can multiply the elements from both lists. For this purpose, we can use Zip Function.
We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.
Multiply Two Python Lists Element-wise Using Numpy, that allows us to multiply two arrays. In order to accomplish this, it would seem that we first need to convert the list to a numpy array. However, numpy handles this implicitly. The method returns a numpy array.
multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.
Use np.prod
:
>>> a = np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> np.prod(a,axis=1)
array([ 6, 24, 60])
Use a list comprehension and reduce
:
>>> from operator import mul
>>> lis = [[1,2,3],[2,3,4],[3,4,5]]
>>> [reduce(mul, x) for x in lis]
[6, 24, 60]
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