[英]Summing up the elements of lists in a for loop
因此, 这里给出我的问题的基础。 毕竟,我需要添加列表中的元素。 在最简单的示例中:
first = [1,2]
second = [6,7]
然后
[x + y for x, y in zip(first, second)]
这使:
#[7,9]
但是我的问题是我通过for循环产生了许多列表。 在for循环中,列表未存储,因此要查看它们,可以在循环末尾使用print(list)
并打印列表。 现在如何编写代码以查看生成的列表并以上述给定方式对元素求和?
例:
l = []
for i in range(2):
l= list(range(5))
print(l)
以上产生:
#[0, 1, 2, 3, 4]
#[0, 1, 2, 3, 4]
我如何在for循环中添加一行以求和列表的一对一元素以得到:
#[0, 2, 4, 6, 8]
使用变量保存总数,并在循环中更新
totals = [0]*5
for i in range(5):
l = list(range(5))
totals = [x + y for x, y in zip(totals, l)]
print totals
或者,您可以将所有列表保存在另一个列表中,然后使用最初的想法:
all_lists = []
for i in range(5):
l = list(range(5))
all_lists.append(l)
totals = [sum(lists) for lists in zip(*all_lists)]
据我了解,这是另一种实现方法,即使用运算符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])
输出:
[0, 2, 4, 6, 8]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.