Search code examples
pythonlist-comprehension

List of lists of tuples, sum element-wise


I have a list of lists of tuples. Each inner list contains 3 tuples, of 2 elements each:

[
[(3, 5), (4, 5), (4, 5)],
[(7, 13), (9, 13), (10, 13)],
[(5, 7), (6, 7), (7, 7)]
]

I need to get a single list of 3 tuples, summing all these elements "vertically", like this:

(3, 5),  (4, 5),  (4, 5)
 +  +     +  +     +  +  
(7, 13), (9, 13), (10, 13)
 +  +     +  +     +  +  
(5, 7),  (6, 7),  (7, 7)
  ||       ||       ||
[(15, 25), (19, 25), (21, 25)]

so, for example, the second tuple in the result list is given by the sums of the second tuples in the initial list

(4+9+6, 5+13+7) = (19, 25)

I'm trying with list/tuple comprehensions, but I'm getting a little lost with this.


Solution

  • You could do this pretty easily with numpy. Use sum on axis 0.

    import numpy as np
    
    l = [
    [(3, 5), (4, 5), (4, 5)],
    [(7, 13), (9, 13), (10, 13)],
    [(5, 7), (6, 7), (7, 7)]
    ]
    
    
    [tuple(x) for x in np.sum(l,0)]
    

    Output

    [(15, 25), (19, 25), (21, 25)]