Python Addition of Two List Values
Task: two lists of numeric values of the same length, the corresponding elements are added to form a new list
1. Use Python's native list completion
list1 = [1, 3, 5] list2 = [2, 4, 6] list3 = [] for i in range(len(list2)): (list1[i] + list2[i]) print(list1) print(list2) print('The list obtained by adding two lists:') print(list3)
Output results:
[1, 3, 5]
[2, 4, 6]
The list obtained by adding two lists:
[3, 7, 11]
2, the use of NumPy provides an array to achieve arithmetic operations
In [6]:import numpy as np In [7]:arr1 = ([1, 3, 5]) In [8]:arr2 = ([2, 4, 6]) In [9]:arr1 + arr2 Out[9]: array([ 3, 7, 11]) In [10]:arr1 - arr2 Out[10]: array([-1, -1, -1]) In [11]:arr1 * arr2 Out[11]: array([ 2, 12, 30]) In [12]:arr1 / arr2 Out[12]: array([0.5 , 0.75 , 0.83333333]) In [13]:arr1 // arr2 Out[13]: array([0, 0, 0], dtype=int32) In [14]:arr1 + 100 Out[14]: array([101, 103, 105]) In [15]:arr1 ** 2 Out[15]: array([ 1, 9, 25], dtype=int32)
Summing two list values in Python
Method 1
Call the map() function using the () method and the list.
This approach requires importing the add() method from the operator module.
The method is the same as a + b, so it is only suitable for two lists, and you need to use the list() class to convert the map object to a list.
from operator import add list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = list(map(add, list1, list2)) print(list3)
Run results:
Method 2
Use the zip function to iterate through multiple iterable objects in parallel so that the corresponding objects generate a tuple, and then pass each tuple to the sum() function to obtain the sum.
This method is suitable for two or more lists.
① Two lists:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = list(zip(list1, list2)) print(list3) # ==print(list(zip(list1, list2))) list_3 = [sum(tup) for tup in zip(list1, list2)] print(list_3)
Run results:
By analogy, the same is written for multiple lists.
② 3 lists:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] list4 = list(zip(list1, list2, list3)) print(list4)
Run results:
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.