如何使用nditer迭代每个操作数的第一个维度?

时间:2013-05-23 15:04:55

标签: python numpy iterator

假设:

import numpy as np
a = np.arange(6)
b = np.arange(24).reshape(6,4)

我想要这样的事情:

for i in xrange(len(a)):
    v1 = a[i]
    v2 = b[i,...]

但我无法弄清楚如何使用nditer?

it = np.nditer((a,b))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-7fe57c985cae> in <module>()
----> 1 it = np.nditer((a,b))

ValueError: operands could not be broadcast together with shapes (6) (6,4) 

这适用于单个操作数,但如何为不同等级的操作数执行此操作?

a = np.arange(6).reshape(2,3)
for x in np.nditer(a, flags=['external_loop'], order='F'):
...     print x,

1 个答案:

答案 0 :(得分:2)

为什么不使用zip

>>> for i in xrange(len(a)):
...     print a[i],b[i,...]
... 
0 [0 1 2 3]
1 [4 5 6 7]
2 [ 8  9 10 11]
3 [12 13 14 15]
4 [16 17 18 19]
5 [20 21 22 23]
>>> for v1,v2 in zip(a,b):
...     print v1,v2
... 
0 [0 1 2 3]
1 [4 5 6 7]
2 [ 8  9 10 11]
3 [12 13 14 15]
4 [16 17 18 19]
5 [20 21 22 23]