Three ways to "add" two lists of numbers in Python

    

Table of contents

for loop

map()

numpy


       Recently, when I was processing data in Python, I needed to add the list data to achieve the "cumulative" effect. It should be noted that the addition of lists I am talking about here is not the case of "addition of list elements" as follows.

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
print(list_1 + list_2)

output:

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

Note: In addition to the + sign, there are methods such as append(), and extend()so on to add list elements.

Our current two list elements are both int integer type, and secondly they have the same length, we want to add the elements corresponding to the index position to generate a new list list_3.

for loop

Enter the following command in the interactive environment:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
list_3 = []

for index, item in enumerate(list_1):
    list_3.append(item + list_2[index])

print(list_3)

 output:

[5, 7, 9]

map() 

map() is a built-in high-order function in Python. It receives a function f and a list, and by applying the function f to each element of the list in turn, a new list is obtained and returned.

Enter the following command in the interactive environment:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

list_3 = list(map(lambda x, y: x + y, list_1, list_2))

print(list_3)

output:

[5, 7, 9]

numpy 

Enter the following command in the interactive environment:

list_1 = [1, 2, 3]
list_2 = [4, 5, 6]

import numpy as np

list_3 = list(np.add(list_1, list_2))

print(list_3)

output:

[5, 7, 9]

 

 

Guess you like

Origin blog.csdn.net/weixin_69333592/article/details/128282859