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

How to relay the sum of each nested list to the next one?

My input is this list :

my_list = [[3, 4, -1], [0, 1], [-2], [7, 5, 8]]

I need to sum the nested list i and pad it to the right of the list i+1, it’s like a relay course.

I have to mention that the original list should be untouched and I’m not allowed to copy it.

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

wanted = [[3, 4, -1], [0, 1, 6], [-2, 7], [7, 5, 8, 5]]

I tried the code below but I got a list with more elements than my original one :

from itertools import pairwise

wanted = []

for left, right in pairwise(my_list):
    wanted.extend([left, right + [sum(left)]])
    
print(wanted)
[[3, 4, -1], [0, 1, 6], [0, 1], [-2, 1], [-2], [7, 5, 8, -2]]

Can you guys explain what’s happening please or suggest another solution ?

>Solution :

You can try itertools.accumulate:

from itertools import accumulate

my_list = [[3, 4, -1], [0, 1], [-2], [7, 5, 8]]

print(list(accumulate(my_list, lambda l1, l2: [*l2, sum(l1)])))

Prints:

[[3, 4, -1], [0, 1, 6], [-2, 7], [7, 5, 8, 5]]
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