0

say we have a l list, it made up of 5 or more element which i want to calculate every nth sum in the list just like a fibonacci sequence

l=[1,5,6,7,2]

finally i would like to have a new list l2 which show the sum of every nth element in the l list

1+5=6
5+6=11
6+7=13
7+2=9
l2=[0,6,11,13,9]

i have tried list2= [sum(l[i:i+i[2]])for i in range(0,len(l),2)] but it says int not scriptable and i try many more just to stuck please help

  • Does this answer your question? [How to find the cumulative sum of numbers in a list?](https://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list) – Mark Jan 06 '20 at 04:01

2 Answers2

0

One way using itertools.tee and pairwise:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

[0, *map(sum, pairwise(l))]

Output:

[0, 6, 11, 13, 9]
Chris
  • 29,127
  • 3
  • 28
  • 51
  • hello chris thank for the answer, but i cant call the function because i made the script without one, so if i add the def pairwise the function dont come up when i run the program – Farhan Jamil Jan 06 '20 at 04:28
0

You could just do a list comprehension from the zip like,

>>> l
[1, 5, 6, 7, 2]
>>> [0] + [x+y for x,y in zip(l, l[1:])]
[0, 6, 11, 13, 9]

or instead of list comprehension, a generation expression like,

>>> [0, *(x+y for x,y in zip(l, l[1:]))]
[0, 6, 11, 13, 9]
han solo
  • 6,390
  • 1
  • 15
  • 19