Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I multiply and sum elements across two lists (without using a library)?

Tags:

python

list

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]]
like image 510
diegus Avatar asked Oct 29 '25 18:10

diegus


2 Answers

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]
like image 78
Mazdak Avatar answered Oct 31 '25 07:10

Mazdak


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]]
like image 24
Hai Vu Avatar answered Oct 31 '25 08:10

Hai Vu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!