I am trying to sum the product of two different list items in the same line using for loop, but I am not getting the output as expected.
My example code:
JavaScript
x
9
1
a = [1,2,3]
2
b = [4,5,6]
3
4
sum = 0 # optional element
5
6
score = ((sum+(a(i)*b(i)) for i in range(len(a)))
7
8
print score
9
output:
JavaScript
1
2
1
<generator object <genexpr> at 0x027284B8>
2
expected output:
JavaScript
1
2
1
32 # 0+(1*4)+(2*5)+(3*6)
2
Advertisement
Answer
Just zip
the lists to generate pairs, multiply them and feed to sum
:
JavaScript
1
5
1
>>> a = [1,2,3]
2
>>> b = [4,5,6]
3
>>> sum(x * y for x, y in zip(a, b))
4
32
5
In above zip
will return iterable of tuples containing one number from both lists:
JavaScript
1
3
1
>>> list(zip(a, b))
2
[(1, 4), (2, 5), (3, 6)]
3
Then generator expression is used to multiply the numbers together:
JavaScript
1
3
1
>>> list(x*y for x, y in list(zip(a, b)))
2
[4, 10, 18]
3
Finally sum
is used to sum them together for final result:
JavaScript
1
3
1
>>> sum(x*y for x, y in list(zip(a, b)))
2
32
3