This sharing will describe how to sum the corresponding elements of multiple lists in Python, provided that the length of each list is the same. For example: a=[1,2,3], b=[2,3,4], c=[3,4,5], sum the corresponding elements of a, b, c, the output should be [6, 9,12].
Method 1:
Direct solution, according to the principle of adding corresponding elements, you can first define a function.
def list_add(a,b):
c = []
for i in range(len(a)):
c.append(a[i]+b[i])
return c
if __name__ == '__main__':
a = [1,2,3]
b = [2,3,4]
c = [3,4,5]
print(list_add(list_add(a,b),c))
Method 2:
Use the numpy module to solve the problem.
import numpy as np
a = np.array([1,2,3])
b = np.array([2,3,4])
c = np.array([3,4,5])
print(a+b+c)
It should be noted that the type after a+b+c is numpy.ndarray.
Method 3:
Use the sum() function of the numpy module to solve.
import numpy as np
a = [1,2,3]
b = [2,3,4]
c = [3,4,5]
print(np.sum([a,b,c], axis = 0))
The axis parameter represents vertical summation.
This sharing ends here, everyone is welcome to communicate~~
**Note:** I have now opened a WeChat public account: Python crawler and algorithm (WeChat ID is: easy_web_scrape), everyone is welcome to pay attention~~