One way is to use the add
ufunc with its reduceat
method:
>>> np.add.reduceat(a, [0,5])
array([15, 40])
This sums the slices a[0:5]
and a[5:]
and returns a new array.
If you want a Python list, you could call tolist()
on the returned array.
You can use any list of indexes with the method (and they do not have to evenly spaced). For example, if you want slices of 5 each time on an array of length 100:
>>> b = np.arange(100)
>>> np.add.reduceat(b, range(0, 100, 5))
array([ 10, 35, 60, 85, 110, 135, 160, 185, 210, 235, 260, 285, 310,
335, 360, 385, 410, 435, 460, 485])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…