I have a numpy array such as arr = np.arange(16).reshape(2,2,2,2)
I want to dynamically access arr[:, dim2, dim3]
, when I have (dim2, dim3)
as a tuple. What is the best way to do this?
Try something like this if the number of dimensions might not be the same for your array:
some_tuple = (dim2, dim3) # Could be (dim2, dim3, ..., dimN)
arr[(slice(None),) + some_tuple]
In this particular case, (slice(None),) + some_tuple
is the same as (slice(None), dim2, dim3)
. slice(None)
is more or less equivalent to " :
", but it can be used in more places than " :
". Notice that I put slice(None)
in a single-element tuple (ie (slice(None),)
) so that I can add it to some_tuple
. Notice as well that there's a comma after slice(None)
, ie, I don't just write (slice(None))
without a comma. It won't work without the extra comma.
some_tuple = (dim2, dim3) arr[:, some_tuple[0], some_tuple[1]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.