我需要將未知數量的列表中的每個索引一起添加到一個列表中。通過索引添加未知數量的列表
我的意思的例子:
list_a = [1,2,3,4,5]
list_b = [2,4,6,8,10]
list_c = [3,6,9,12,15]
def sum_lists():
temp_list = []
for index in range(len(list_a)):
temp_list.append(list_a[index] + list_b[index] + list_c[index])
return temp_list
total = sum_lists()
我的示例代碼的預期結果將是:
total = [6,12,18,24,30]
我將如何完成列表的未知量的總和,例如20個列表?我不需要在數以千計的列表中添加這些內容,但我不知道最初必須添加多少個列表。
任何幫助將不勝感激。所有的列表將具有相同的長度。
如果你要得到一個列表的總和(如:'[1,2,3]→6') ,你會怎麼做? – Ryan
'郵編'的名單。在得到的元組列表中,對每個元組的元素進行求和。查看如何使用'zip'和'sum'方法。 – Prune
'[zip(list_a,list_b,list_c)]中的els的總和(els)]。正如@Prune所說,它使用['sum'](https://docs.python.org/3/library/functions.html#sum)和['zip'](https://docs.python.org /3/library/functions.html#zip)內置方法。 –