簡體   English   中英

總結for循環中列表的元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM