更新时间:2022-12-01 14:15:48
We could use an almost vectorized approach based upon np.add.reduceat
that takes care of the irregular length subarrays, for which we are calculating the average values. np.add.reduceat
sums up elements in those intervals of irregular lengths after getting a 1D
flattened version of the input array with np.concatenate
. Finally, we need to divide the summations by the lengths of those subarrays to get the average values.
因此,实现看起来像这样-
Thus, the implementation would look something like this -
lens = np.array(map(len,foo)) # Thanks to @Kasramvd on this!
vals = np.concatenate(foo)
shift_idx = np.append(0,lens[:-1].cumsum())
out = np.add.reduceat(vals,shift_idx)/lens.astype(float)