Reputation: 23
I have a list of index tuples for all dimensions of an array bar the first two.
For each index tuple, I would like to return a slice of the array at this tuple position.
I don't know in advance the number of dimensions in the array, or equivalently the number of elements in the index tuple.
For example, if there were two elements in the index tuple (pos
) I would write something like:
arr[:, :, pos[0], pos[1]]
to return a slice of the array at this position. I would like to be able to do this without knowing in advance the length of pos. Naively, I thought arr[:, :, *pos]
would work, but of course it doesn't.
Thanks for the help.
Upvotes: 2
Views: 162
Reputation: 336
You can concatenate the Ellipsis
with your tuple p
, to obtain the tuple Ep
that can be used to slice the array:
Ep = (Ellipsis,)+p
sliced_arr = arr[Ep]
Edit: kudos to the previous answer (which has been deleted) for mentioning the Ellipsis
, which is really half of my answer here.
Upvotes: 1