I am trying to calculate the sum of elements in a list of lists. I have no trouble in computing the sum if the lists within the main list all have the same size, like below:
a = [[4], [8], [15]]
total = [sum(i) for i in zip(*a)]
result:
total = [27] #(4 + 8 + 15) = 27, GOOD!!!
however there is a chance that I may have a list with a different size within the main list, such as:
a = [[3], [4, 6], [10]]
expected result:
total = [17, 19] #(3 + 4 + 10) = 17, (3 + 6 + 10) = 19
I got stuck here, obviously my solution for the lists of equal sizes does not work. What would be the best way to get the result the way I defined? My intuition was figuring out the list with the maximum length, then expanding other lists to that length with adding zeros, and finally computing the sums separately. This sounds like an ugly solution though, and I wonder if there is there a quick and more elegant way to do this.
Thanks!
EDIT: Should have explained it better. I got confused a bit too... Here below are better examples:
The number of elements in the lists within the list a
never exceeds 2. Examples:
a = [[1], [10], [5]] #Expected result: [16] (1+10+5)
a = [[1, 10], [3], [4]] #Expected result: [8, 17] (1+3+4, 10+3+4)
a = [[1, 10], [3], [2, 8]] #Expected result: [6, 12, 15, 21] (1+3+2, 1+3+8, 10+3+2, 10+3+8)
EDIT2: Accepted answer computes the correct results independent of the list sizes.