Reputation: 1188
I've two lists (m1 and m2) containing lists of numbers. I'm trying to do element-wise multiplication and sum including the cross product to obtaining a final list (result) as follow:
m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[7, 9, 2], [8, 1, 3]]
[[1*7+2*9+3*2,1*8+2*1+3*3],[4*7+5*9+6*2,4*8+5*1+6*3]]
result = [[31,19],[85,55]]
Upvotes: 4
Views: 7323
Reputation: 10961
If you want it without importing any modules, you can do it this way:
>>> m1 = [[1, 2, 3], [4, 5, 6]]
>>> m2 = [[7, 9, 2], [8, 1, 3]]
>>> [[sum(map(lambda (s,t):s*t, zip(x,y))) for y in m2] for x in m1]
[[31, 19], [85, 55]]
Upvotes: 1
Reputation: 107347
You can play with python built-in functions and a nested list comprehension :
>>> [[sum(t*k for t,k in zip(i,j)) for j in m2] for i in m1]
[[31, 19], [85, 55]]
You can also use itertools.product
to find the products between sub-lists :
>>> from itertools import product
>>> [sum(t*k for t,k in zip(i,j)) for i,j in product(m1,m2)]
[31, 19, 85, 55]
Upvotes: 7
Reputation: 40773
Let's break the problem into the smaller pieces. At the lowest level, we have two small lists: [1, 2, 3]
and [7, 9, 2]
and want to multiply them, item by item:
item1 = [1, 2, 3]
item2 = [7, 9, 2]
zip(item1, item2) # ==> [(1, 7), (2, 9), (3, 2)]
[x * y for x, y in zip(item1, item2)] # ==> [7, 18, 6]
sum(x * y for x, y in zip(item1, item2)) # ==> 31
Now, we can put this to work inside a double loop:
[[sum(x * y for x, y in zip(item1, item2)) for item2 in m2] for item1 in m1]
# ==> [[31, 19], [85, 55]]
Upvotes: 5