Home > Enterprise >  Python efficient/simple ways to calculate the sum of two array of values?
Python efficient/simple ways to calculate the sum of two array of values?

Time:10-22

For example, I need to find the sum of the products of two lists of numbers:

numbers=[1,2,3]
numba = [4,5,6]

result = []
for list1,list2 in zip(numbers,numba):
    f_1 = float(list1)
    f_2 = float(list2)
    pro = f_1 * f_2
    result.append(pro)
print(sum(result))

Currently I have to create a new list outside the for loop to proceed getting the sum of the product values. So I am curious are there more efficient ways in default Python to get the sum without setting up a new list to store the products in order to perform calculations?

(Mathematically the formula would be a*a2 b*b2 c*c2)

CodePudding user response:

You can use (generator) comprehension to simplify the task.

numbers=[1,2,3]
numba = [4,5,6]

print(sum(x * y for x, y in zip(numbers, numba))) # 32

CodePudding user response:

You don't need to store a list, you can just keep track of the total:

numbers = [1, 2, 3]
numba = [4, 5, 6]

result = 0.0
for a, b in zip(numbers, numba):
    result  = a * b

print(result)

CodePudding user response:

Using reduce and map:

from functools import reduce
from operator import add,mul

numbers=[1,2,3]
numba = [4,5,6]
print(reduce(add,map(mul,numbers,numba)))

Output:

32
  • Related