【发布时间】:2019-05-07 06:46:59
【问题描述】:
我在 python 中有一个 3D ndarray,并希望以元素方式沿三个边距中的两个对其进行迭代。
更确切地说,例如,我想遍历所有 (x,y) 对,但将 z 数据作为数组保存在一起。
作为伪代码,我最终追求的表达方式是这样的
[ f(z) for z in all_xy_pairs(the_ndarray) if g(z) == True ]
我考虑过如下使用'reshape'
import numpy as np
# silly example
ii=np.arange(0,3*9,1).reshape(3,3,3)
[ z for z in ii.reshape(9,-1) if z[1]>10 ]
但我更喜欢一个迭代器,我可以将数组边距传递给它进行迭代(在上面的示例中,margins=[0,1]。在伪代码中,上面的示例将变为
[ z for z in iterate_over_margins(ii, margins=[0,1]) if z[1]>10 ]
在我开始自己编程之前,numpy 或相关包中没有这样的迭代器吗?我检查了nditer,但它并没有达到我想要的效果。
【问题讨论】:
-
z[i,:,j] for i in range(z.shape[0]) for j in range(z.shape[2])有什么问题? -
谢谢,这当然有效。我会接受这个作为答案。