简体   繁体   English

总结for循环中列表的元素

[英]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. 但是我的问题是我通过for循环产生了许多列表。 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. 在for循环中,列表未存储,因此要查看它们,可以在循环末尾使用print(list)并打印列表。 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: 我如何在for循环中添加一行以求和列表的一对一元素以得到:

#[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 . 据我了解,这是另一种实现方法,即使用运算符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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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