D B D B - 1 year ago 69
Python Question

Add together elements up to certain index

So I have an array

[1,2,3,4,5,6,7,8,9,10]

and I need to create a new array that adds together the first
5
elements then the next
5
elements, ect. so
1+2+3+4+5=15
,
6+7+8+9+10=40
[15,40]
. How would i go about doing this?

Answer Source

you can do something like :

>>> l1 =  [1,2,3,4,5,6,7,8,9,10]
>>> l2= [sum(l[n:n+5]) for n in range(0, len(l), 5)]
>>> l2
[15, 40]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download