Using numpy
, you can reshape your list of 18 elements into an array of shape (6, 3)
and then take the mean over the rows
import numpy as np
a = np.array(first)
>>> a.reshape(-1, 3)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18],
>>> a.reshape(-1, 3).mean(axis=1)
array([ 2., 5., 8., 11., 14., 17.])
The use of -1
in np.reshape(-1, 3)
actually allows you to use this approach for any array whose size is a multiple of 3 and it will automatically size the first dimension appropriately