How to add odd sub-lists in Python?

So, let's say I have a list with sub-lists (alignment for visual demonstration):

[[1,2,3,4], [1,2,3], [0,3,4]] 

And I want to add them together to get:

 [2,7,10,4] 

Initially, for what I was working on, I knew the top border of these lists, I thought of iterating through each sub-list and indented 0 and composing each list until the top border:

 result+=[0]*(len(upper_bound)-len(list)) 

Then use:

 result = [sum(x) for x in zip(list1,list2) 

to get the amount. But the upper bound becomes very large (for example, 10000+), and the number of lists is also a lot (for example, 1000+).

My question is: is there a more efficient method of adding N potentially uneven subscriptions to give a resulting list, or am I asking too much? (I also can't use any fantastic number libraries like numpy)

+4
source share
1 answer

itertools.izip_longest can do what you need:

 import itertools lists = [[1,2,3,4], [1,2,3], [0,3,4]] print [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)] # prints [2, 7, 10, 4] 
+7
source

Source: https://habr.com/ru/post/1445182/


All Articles