Sums of variable size chunks of a list where sizes are given by other list

You can make use of np.bincount with weights:

groups = np.repeat(np.arange(len(b)), b)

np.bincount(groups, weights=a)

Output:

array([ 1.,  9., 35.])

NumPy has a tool to do slice based sum-reduction with np.add.reduceat -

In [46]: np.add.reduceat(a,np.cumsum(np.r_[0,b[:-1]]))                          
Out[46]: array([ 1,  9, 35])

You mean something like this?

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [2, 3, 5]

def some_function(a, b): # couldnt come up with a name :D
    last_index = 0

    for i in b:
        print(sum(a[last_index:last_index + i]))
        last_index += i

some_function(a, b)

Tags:

Python

Numpy