current position:Home>Summation of corresponding position elements of multiple lists in Python

Summation of corresponding position elements of multiple lists in Python

2022-05-15 02:36:02ctrl A_ ctrl C_ ctrl V

I thought it was a very simple question , I didn't expect to make mistakes .

If we want to achieve : [1,2,3]+[4,5,6]=[5,7,9] How do you do that ?

I naturally think of adding directly , But it's wrong :

print([1,2,3]+[4,5,6])    # [1, 2, 3, 4, 5, 6]

You can find , The direct addition of two lists is equivalent to append, Instead of adding the corresponding position elements we want .

The same problem occurs when the list elements are multiplied by the same number at the same time , If you want to be right [1,2,3] And multiply it by 3, direct [1,2,3]*3 What you get is not [3,6,9]

print([1,2,3]*3)    # [1, 2, 3, 1, 2, 3, 1, 2, 3]

The right thing to do is :

a=[1,2,3]
print([3*i for i in a])    # [3, 6, 9]

To achieve the addition of corresponding position elements , It should be written like this :

a = [1, 2, 3]
b = [4, 5, 6]
result = [i + j for i, j in zip(a, b)]
print(result)    # [5, 7, 9]

And so on , More lists can also be added :

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
result = [i + j + k for i, j, k in zip(a, b, c)]
print(result)     # [12, 15, 18]

copyright notice
author[ctrl A_ ctrl C_ ctrl V],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/135/202205142112580270.html

Random recommended