Reputation: 61
I found that summing a list of list of number is:
In [9]: l = [[3,7,2],[1,4,5],[9,8,7]]
In [10]: [sum(i) for i in zip(*l)]
Out[10]: [13, 19, 14]
However I have been struggling to find a way to sum a list of list of tuples to result in a list of tuples
In [9]: l = [[(1, 1), (1, 1), (1, 1)],[(2, 2), (2, 2), (2, 2)]]
In [10]: [(sum(i[0]), sum(i[1])) for i in zip(*l)] #Did not work
This is my desired output:
Out[10]: [(3, 3), (3, 3), (3, 3)]
Thanks!
Upvotes: 2
Views: 201
Reputation: 12515
You could flatten the iterable recursively first
>>> import collections
>>>
>>> def flatten(l):
... for el in l:
... if isinstance(el, collections.Iterable) and not isinstance(el, str):
... for sub in flatten(el):
... yield sub
... else:
... yield el
...
>>> sum(flatten(l))
18
See this link for more details on flatten
.
Upvotes: 1
Reputation: 164613
You can use a tuple
comprehension within a list comprehension:
L = [[(1, 1), (1, 1), (1, 1)], [(2, 2), (2, 2), (2, 2)]]
res = [tuple(sum(j) for j in zip(*i)) for i in zip(*L)]
[(3, 3), (3, 3), (3, 3)]
Or use map
for a more functional alternative:
res = [tuple(map(sum, zip(*i))) for i in zip(*L)]
For larger lists, you may wish to consider a 3rd party library such as NumPy where, in NumPy terminology, you need only sum over a specified axis:
import numpy as np
A = np.array(L)
res = A.sum(axis=0)
array([[3, 3],
[3, 3],
[3, 3]])
Upvotes: 2