简体   繁体   中英

Summing up the elements of lists in a for loop

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]

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)]

From what I understand, here is another way of doing it ie 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM