preamble
Recently, when I use Python to process data, I need to add the list of data to realize the "accumulation" effect. Note that what I mean by adding lists here is not the following "adding list elements together" scenario.
list_1 = [1, 2, 3] list_2 = [4, 5, 6] print(list_1 + list_2)
Output:
[1, 2, 3, 4, 5, 6]
Note: The list elements are added in a way that, in addition to the + sign, there is theappend()
、 extend()
and other methods.
Both of our current list elements are int integers, and secondly they are of the same length, so we want to add the elements at the corresponding index positions to generate a new listlist_3
。
Just in time to review Python basics and talk about the 4 ways to add two list numbers.
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]
list generator
Enter the following command in the interactive environment:
list_1 = [1, 2, 3] list_2 = [4, 5, 6] [x + y for x, y in zip(list_1, list_2)]
Output:
map()
map()
is a built-in higher-order function in Python that takes a function f and a list, and returns a new list by applying the function f to each element of the list in turn.
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((list_1, list_2)) print(list_3)
Output:
[5, 7, 9]
summarize
to this article on Python in the two lists of numbers added to the four methods of the article is introduced to this, more related to Python list of numbers added to the contents of the search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!