hpnk85 hpnk85 - 4 months ago 6
Python Question

group elements in an array and sum

I have the following array

a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]


I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum

b = [1,0,2,0,3,0,1]


Any suggestions?

Answer

Maybe something like this:

a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
b = []

for i in range(0,len(a),3):
    b.append(sum(a[i:i+3]))
print b

Output:

[1, 0, 2, 0, 3, 0, 1]