user973758
user973758

Reputation: 727

Python multiply list of lists element-wise

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]

Upvotes: 5

Views: 3462

Answers (3)

inspectorG4dget
inspectorG4dget

Reputation: 113955

import operator
import functools
answer = [functools.reduce(operator.mul, subl) for subl in L]

Or, if you prefer map:

answer = map(functools.partial(functools.reduce, operator.mul), L)  # listify as required

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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]

Upvotes: 3

Daniel
Daniel

Reputation: 19547

Use np.prod:

>>> a = np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> np.prod(a,axis=1)
array([ 6, 24, 60])

Upvotes: 6

Related Questions