Reputation: 31504
What's the best way to sum two or more lists even if they have different lengths?
For example I have:
lists = [[1, 2], [0, 3, 4], [5]]
and the result should be:
result = [6, 5, 4]
Upvotes: 12
Views: 5720
Reputation: 1
This worked well for lists with a thousand and a bit elements. checking with if statements weather to append took ages and ages but this ran pretty fast.i had a function,"longestlist" , that identified and returned the longest list but that's pretty easy to write so using that output...
def listfiller(a,b,c,d)
longest = longestlist(a,b,c,d)
for i in range(len(longest)-len(a)):
a.append(0)
for i in range(len(longest)-len(b)):
b.append(0)
print(b)
for i in range(len(longest)-len(c)):
c.append(0)
for i in range(len(longest)-len(d)):
d.append(0)
return(a,b,c,d)
Upvotes: 0
Reputation: 21
#You can do the same without using predefined header files.
def sumlists(a,b,c):
sumlist = []
while(len(a)!=len(b) or len(a)!=len(c)):
if len(a)>len(b):
b.append(0)
if len(a)>len(c):
c.append(0)
elif len(b)>len(a):
a.append(0)
if len(b)>len(c):
c.append(0)
elif len(c)>len(a):
a.append(0)
if len(c)>len(b):
b.append(0)
for i,j,k in zip(a,b,c):
sumlist.append(i+j+k)
return sumlist
print(sumlists([1,2],[0,3,4],[5]))
Upvotes: 2
Reputation: 31504
The best I came up with is the following:
result = [sum(filter(None, i)) for i in map(None, *lists)]
It's not so bad, but I have to add NoneTypes and then filter them in order to sum up.
Upvotes: 0
Reputation: 250961
You can use itertools.izip_longest()
, and use a fillvalue
equal to 0
In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
Out[6]: [6, 5, 4]
for 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]
Upvotes: 19