Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading