If I have a list of lists, and each nested list contains numbers, how can I add all of these lists element-wise into a single array?
i.e.
listOne = [1, 2, 3]
listTwo = [4, 5, 6]
listThree = [7, 8, 9, 10]
allLists = [listOne, listTwo, listThree]
total = add(allLists)
print total
output should be [12, 15, 18, 10]
Use izip_longest to remap rows/columns (like zip but to the longest element rather than shortest), filling shorter items 0
from itertools import izip_longest
total = [sum(x) for x in izip_longest(*allLists, fillvalue=0)]
Outputs:
[12, 15, 18, 10]
Also for your edification, the intermediate output of the zip_longest is:
[(1, 4, 7), (2, 5, 8), (3, 6, 9), (0, 0, 10)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With