或者重塑y
for i in y.reshape(-1,3):
print i
双重迭代也有效:
for x in y:
for z in x:
print z
Plain nditer
迭代每个元素y
(nditer
不给你索引):
for i in np.nditer(y):
print i
# wrong y[i]
您需要深入了解以下内容的标志和文档nditer
迭代其维度的 2 个。尽管nditer
提供对底层迭代机制的访问,您通常不需要使用它 - 除非您正在做一些不寻常的事情,或者尝试使用cython
.
下面是一个从迭代中获取 2 个值的示例nditer
目的。数组中的每个数组都有一个值op
列表。两个都x
and z
are ()
形状数组。
for x,z in np.nditer([y,y]):
print x,z
关于使用还有更多nditer
at
http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html 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
进行这种浅层迭代,但这值得吗?
In 迭代 numpy 数组的前 d 轴 https://stackoverflow.com/questions/25249380,我偶然发现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
uses 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
I get:
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]