hpnk85 hpnk85 - 1 year ago 79
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 Source

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):
print b


[1, 0, 2, 0, 3, 0, 1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download