Reputation: 47
So the basis of my question is given here. After all I need to add elements of the lists. In the simplest example:
first = [1,2]
second = [6,7]
Then
[x + y for x, y in zip(first, second)]
which gives:
#[7,9]
However my problem is that I am producing number of lists via a for loop. In the for loop the lists are not being stored and so to see them one uses print(list)
at the end of the loop and it prints the lists. Now how can I write a code to look at the produced lists and sum the elements in the given manner above?
Example:
l = []
for i in range(2):
l= list(range(5))
print(l)
the above produces:
#[0, 1, 2, 3, 4]
#[0, 1, 2, 3, 4]
How can I add a line in the for loop to sum the one-by-one elements of the lists to get:
#[0, 2, 4, 6, 8]
Upvotes: 0
Views: 49
Reputation: 1691
From what I understand, here is another way of doing it i.e. using operator add
.
from operator import add
n=5
l = [0]*n
for i in range(2):
l = map(add, l, range(n))
print([x for x in l])
Output:
[0, 2, 4, 6, 8]
Upvotes: 0
Reputation: 780698
Use a variable to hold the totals, and update it in the loop
totals = [0]*5
for i in range(5):
l = list(range(5))
totals = [x + y for x, y in zip(totals, l)]
print totals
Or you can save all your lists in another list, and then use your original idea:
all_lists = []
for i in range(5):
l = list(range(5))
all_lists.append(l)
totals = [sum(lists) for lists in zip(*all_lists)]
Upvotes: 1