开发者

Indexing numpy arrays with different number of dimensions

开发者 https://www.devze.com 2023-04-04 09:51 出处:网络
I am usin开发者_StackOverflowg numpy and I want to store the result of a calculation inside a three or four-dimensional matrix. I want to do something like this:

I am usin开发者_StackOverflowg numpy and I want to store the result of a calculation inside a three or four-dimensional matrix. I want to do something like this:

result[:, indices, iteration] = some_function()  # won't work

where the dimension is understood from the length of the indices tuple. So if indices equals, say, (6,) or (8, 5) then I want to have the equivalent of

result[:, 6, iteration] = some_function()

or

result[:, 8, 5, iteration] = some_function()

Normally I'd put all of the coordinates into a tuple and use that as an index, but the presence of : prevents me from doing that.

The dimension of result has been set earlier to the correct dimension, so can check it, but it would be nice to only use the length of indices to determine it. Is there some way to accomplish this?


Try using result[(slice(None),) + indices + (iteration,)]


If you need to know the length of indices :

len(indices)

But is it this your question ?

0

精彩评论

暂无评论...
验证码 换一张
取 消