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.
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]]