Transposing is cheap (in time). There are numpy functions that use it to move a working axis (or axes) to a known location — usually the front or the end of a list of shapes. tensordot is one that comes to mind.
Other functions build an indexing tuple. They can start with a list or array for easy manipulation, and then turn it into a tuple for the application. for instance
I = [slice(None)]*A.ndim I[axis] = idx A[tuple(I)]
np.apply_along_axis does something similar. It is instructive to look at the code for such functions.
I believe that the authors of numpy functions were most worried about whether it works decisively, and secondly, about speed and, finally, whether it looks beautiful. You can bury all kinds of ugly code in a function!
tensordot ends on
at = a.transpose(newaxes_a).reshape(newshape_a) bt = b.transpose(newaxes_b).reshape(newshape_b) res = dot(at, bt) return res.reshape(olda + oldb)
where the previous code is calculated by newaxes_.. and newshape...
apply_along_axis builds an index tuple (0...,:,0...)
i = zeros(nd, 'O') i[axis] = slice(None, None) i.put(indlist, ind) ....arr[tuple(i.tolist())]
source share