Realization of python for Sum of Product of Corresponding Elements in List

  • 2021-10-16 02:14:46
  • OfStack

On that day, I occasionally saw a small problem: two unequal length lists a= [1, 2, 3] and b= [4, 5, 6, 7], and find the sum of the products of their corresponding elements.

The way I first thought of was to choose a smaller array as the loop length and multiply it and sum it:


a = [1,2,3]
b = [4,5,6,7]
sum = 0
for i in range(0,min(len(a),len(b))):
 number += a[i]*b[i]
print(sum)

But then I thought of a more ingenious method, using the function zip ():


a = [1,2,3]
b = [4,5,6,7]
all = zip(a,b)
num = 0
for i,j in all:
 num += i*j
print(num)

The results of the two methods are exactly the same

The zip () function wraps the list as a tuple list, as in the above two lists:


a = [1,2,3]
b = [4,5,6,7]
all = zip(a,b)

At this time, "all" is actually in this form:

[(1, 4), (2, 5), (3, 6)]

Very interesting small example, by the way, I learned a function

Supplement: Python calculates the product of list elements

Define a list of numbers and calculate the product of list elements.

For example:

Input: list1 = [1, 2, 3]
Output: 6
Calculation: 1 * 2 * 3
Example 1


def multiplyList(myList) :
   
  result = 1
  for x in myList:
     result = result * x 
  return result 
   
list1 = [1, 2, 3] 
list2 = [3, 2, 4]
print(multiplyList(list1))
print(multiplyList(list2))

The output result of the above example is:

6
24

Take a recursive approach:


def list_product(list_1,size):
  if size == 0:
    return 1  
  else:
    return list_1[size-1] * list_product(list_1,size - 1)


list_1 = [i for i in range(3,6)] # Generate list [3,4,5]
print(list_1)
print(list_product(list_1,len(list_1)))

Related articles: