2

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.

1
  • Are the elements of index integers or a lists? Commented Jun 14, 2018 at 15:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is much smarter than what I was trying to do
* expansion does work inside a tuple, e.g. arr[(Ellipsis, *p)].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.