在Python中,是否可以一次返回多个3D阵列切片,而无需循环?
这是示例代码。我想找到一次运行最后两行并立即以同一数组返回结果的方式,而无需串联,这是否可以吗?
import numpy as np
arr = np.ones((3,3,3))
arr[0:2,0:2,0:2]
arr[1:3,1:3,1:3]
结果命令应像是结果
arr[(0:1,2:3),(0:1,2:3),(0:1,2:3)]
,结果的维度为(2,2,2,2)。
Here is example code. I want to find the way to run the last two lines at once and return the results in the same array all at once without concatenation, is this possible?
import numpy as np
arr = np.ones((3,3,3))
arr[0:2,0:2,0:2]
arr[1:3,1:3,1:3]
The resulting command should be like
arr[(0:1,2:3),(0:1,2:3),(0:1,2:3)]
And the dimensionality of the results will be (2,2,2,2).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的数组和切片:
a1
和a2
是views
,与arr
共享数据库。在新维度上加入它们(
np.stack
也将执行此操作):请注意,扁平值不是连续的(或其他常规模式)。因此,他们必须进行某种形式的副本:
一种替代方法是构造索引,加入它们,然后进行一个索引。那个时候大约相同。在这种情况下,我认为这会更加复杂。
===
stride_tricks的另一种方式。我不会向速度保证任何事情。
Your array and slices:
a1
anda2
areviews
, sharing the databuffer witharr
.Joining them on a new dimension (
np.stack
will also do this):Notice how the flattened values are not contiguous (or other regular pattern). So they have to a copy of some sort:
An alternative is to construct the indices, join them, and then do one indexing. That times about the same. And in this case I think that would be more complicated.
===
Another way with stride_tricks. I won't promise anything about speed.