如何将不确定数量的列表加在一起并输出单个列表?

时间:2018-11-11 15:20:34

标签: python

输入将是列表(列表的数量是不确定的),该函数应迭代所有索引,并为所有输入列表在数学上将相同索引的列表的每个值相加。输出将是一个列表,其中包含所有添加的值

例如: lista = [1,2,3] listb = [2,3,5] listc = [-3,2,1] 输出列表= [0,7,9] 我下面的功能只能将2个列表加在一起,我不希望有多少个列表限制。我怎么做? 预先非常感谢

def listadd(a,b):
    counter = 0
    list = []
    while counter < len(a):
        list.append(a[counter]+b[counter])
        counter += 1
    return list

1 个答案:

答案 0 :(得分:2)

您可以将mapzip结合使用:

def listadd_new(*lsts):
    return list(map(sum, zip(*lsts)))

assert listadd([1, 2, 3], [4, 5, 6]) == listadd_new([1, 2, 3], [4, 5, 6])