method 1:
The map() function is called with the operator.add() method and a list. This way of writing needs to import the add() method from the operator module. The operator.add method is the same as a + b, so it is only suitable for two lists, and the obtained result needs to use the list() class to convert the map object into a list.
from operator import add
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list(map(add, list1, list2))
print(list3)
operation result:
Method 2:
Use the zip function to iterate multiple iterable objects in parallel, make the corresponding objects generate a tuple, and then pass each tuple to the sum() function to get the sum. This method works well 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)
Running results:
By analogy, the same way is written when there are multiple lists.
②3 lists:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
list4 = list(zip(list1, list2, list3))
print(list4)
Running results:
The above is a summary of personal learning, which is limited to communication and sharing, and will continue to be updated if there are supplements in the future.