-1

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?

hpnk85
  • 395
  • 1
  • 7
  • 12

4 Answers4

3

Simply, most pythonicly would be the following

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

where your input array is a.

>>> a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
>>> b = [sum(a[i:i+3]) for i in range(0, len(a), 3)]
>>> b
[1, 0, 2, 0, 3, 0, 1]
intboolstring
  • 6,891
  • 5
  • 30
  • 44
3

You can split in chunk and sum:

step = 3
[sum(a[i:i+step]) for i in range(0, len(a),step)]
[1, 0, 2, 0, 3, 0, 1]

If the length is not the multiple of step, last chunk might be smaller.

DurgaDatta
  • 3,952
  • 4
  • 27
  • 34
2

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

Another option using groupby from itertools:

from itertools import groupby
[sum(v for _, v in g) for _, g in groupby(enumerate(a), key = lambda x: x[0]/3)]
# [1, 0, 2, 0, 3, 0, 1]

Or another way to use zip:

[sum(v) for v in zip(a[::3], a[1::3], a[2::3])]
# [1, 0, 2, 0, 3, 0, 1]
Psidom
  • 209,562
  • 33
  • 339
  • 356