enr*_*cis 11 python algorithm sum list
即使它们有不同的长度,对两个或多个列表求和的最佳方法是什么?
例如,我有:
lists = [[1, 2], [0, 3, 4], [5]]
Run Code Online (Sandbox Code Playgroud)
结果应该是:
result = [6, 5, 4]
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 18
你可以使用itertools.izip_longest(),并使用fillvalue等于0
In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
Out[6]: [6, 5, 4]
Run Code Online (Sandbox Code Playgroud)
对于Python <2.6:
In [27]: ml = max(map(len, lists))
In [28]: ml #length of the longest list in lists
Out[28]: 3
In [29]: [sum(x) for x in zip(*map(lambda x:x+[0]*ml if len(x)<ml else x, lists))]
Out[29]: [6, 5, 4]
Run Code Online (Sandbox Code Playgroud)