或重塑y
for i in y.reshape(-1,3):
print i
双重迭代也可以:
for x in y:
for z in x:
print z
普通的nditer 迭代y 的每个元素(nditer 不给你索引):
for i in np.nditer(y):
print i
# wrong y[i]
您需要深入了解nditer 的标志和文档,以迭代其2 个维度。虽然nditer 提供了对底层迭代机制的访问权限,但您通常不需要使用它——除非您正在做一些不寻常的事情,或者尝试使用cython 加速代码。
这是一个从 nditer 对象的迭代中获取 2 个值的示例。 op 列表中的每个数组都有一个值。 x 和 z 都是 () 形状数组。
for x,z in np.nditer([y,y]):
print x,z
关于nditer 的使用的更多信息,请访问
http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html
此文档页面有一个使用 external_loop 的示例,该示例将数组放入子数组中,而不是单独列出。我可以通过重新排序其轴来完成 3d y 的相同操作:
y3=y.swapaxes(2,0).copy(order='C')
for i in np.nditer(y3,order='F',flags=['external_loop']):
print i,
[242 14 211] [198 7 0] [235 60 81] [164 64 236]
所以我们可以使用nditer 来做这个浅层迭代,但这值得吗?
在Iterating over first d axes of numpy array,我偶然发现了ndindex:
for i in np.ndindex(y.shape[:2]):
print y[i],
# [242 14 211] [198 7 0] [235 60 81] [164 64 236]
ndindex 使用nditer。生成浅层迭代的技巧是使用仅使用要迭代的维度的子数组。
class ndindex(object):
def __init__(self, *shape):
...
x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape))
self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'], order='C')
def __next__(self):
next(self._it)
return self._it.multi_index
或者去掉ndindex的基本部分我得到:
xx = np.zeros(y.shape[:2])
it = np.nditer(xx,flags=['multi_index'])
while not it.finished:
print y[it.multi_index],
it.iternext()
# [242 14 211] [198 7 0] [235 60 81] [164 64 236]