Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum element by element multiple lists of different lengths

Is there any way to sum over multiple lists, index by index, to get one final list? Knowing that these lists might not have the same length? For example, with these

[2,4,0,0], [0,0,2], [0,4]

I would like to have

[2,8,2,0] 

as a result.

I haven't found any result so far.

like image 267
Anthony Avatar asked Jan 07 '23 20:01

Anthony


1 Answers

You can use itertools.zip_longest with the fillvalue argument set to 0. If you use this in a list comprehension, you can unpack and zip the inner lists and add them in an element-wise fashion.

>>> from itertools import zip_longest
>>> [sum(i) for i in zip_longest(*l, fillvalue=0)]
[2, 8, 2, 0]
like image 175
Cory Kramer Avatar answered Jan 18 '23 23:01

Cory Kramer