How can I sum the product of two list items using for loop in python?

I am trying to summarize the product of two different list items on the same line, using for a loop, but I am not getting the output as expected.

My sample code is:

a = [1,2,3]
b = [4,5,6]

sum = 0              # optional element

score = ((sum+(a(i)*b(i)) for i in range(len(a)))

print score

output:

<generator object <genexpr> at 0x027284B8>

Expected Result:

32                   # 0+(1*4)+(2*5)+(3*6)
+4
source share
7 answers

Just ziplists to create pairs, multiply them and feed in sum:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(x * y for x, y in zip(a, b))
32

The above zipwill return an iterable tuple set containing one number from both lists:

>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]

Then the generator expression is used to multiply the numbers together:

>>> list(x*y for x, y in list(zip(a, b)))
[4, 10, 18]

Finally, sumused to sum them for the final result:

>>> sum(x*y for x, y in list(zip(a, b)))
32
+6
source

, , [], -, , .

zip :

In [3]: sum(i*j for i,j in zip(a, b))
Out[3]: 32

operator.mul map sum:

In [11]: from operator import mul 

In [12]: sum(map(mul, a, b))
Out[12]: 32
+3

, , . - , , .

, for, :

score = 0
for i in range(len(a)):
  score = score + a[i]*b[i]

, , Pythonic, , zip , sum, :

score = sum([x*y for (x,y) in zip(a,b)])

reduce ( , import functools, Python 3):

score = reduce(lambda s,t: s+t[0]*t[1], zip(a,b), 0)
+3

:

score = ((sum+(a(i)*b(i)) for i in range(len(a)))

. . , , ,

score = (a[i]*b[i] for i in range(len(a)))

( , , .)

score , "" a b.

- , :

for x in score:
    sum += x
print(sum)

As others have already written, you can do it all on one line with zip()and with sum()built-in functions:

sum([x*y for x, y in zip(a, b)])
+2
source
a = [1,2,3]
b = [4,5,6]
ls = [x * y for x, y in zip(a, b)]
x = sum(ls) 
print x
+1
source

You can try:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(map(lambda x: x[0] * x[1], zip(a, b)))
32
0
source

If you have a large list, you might consider using a scalar product using arrays

import numpy as np
arr1 = np.random.randint(0,2,300)
arr2 = np.random.randint(0,2500,300)

list1 = list(arr1)
list2 = list(arr2)

%timeit sum([x * y for x, y in zip(list1,list2)])

38.9 µs ± 795 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit arr1 @ arr2

1.23 µs ± 89.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
0
source

Source: https://habr.com/ru/post/1667607/


All Articles