2017-02-09 48 views
2

我想使用numpy.ndarray迭代器的flatiter.coords属性,但我遇到了奇怪的行为。考虑简单的程序在numpy中,为什么flatiter访问过ndarray的末尾?

xflat = np.zeros((2, 3)).flat 

while True: 
    try: 
     print(xflat.coords) 
     xflat.next() 
    except StopIteration: 
     break 

此代码产生以下输出:

(0, 0) 
(0, 1) 
(0, 2) 
(1, 0) 
(1, 1) 
(1, 2) 
(2, 0) 

最后一个坐标是无效的 - 没有(2,0)的坐标。这意味着我不能进一步检查使用flatiter.coords属性,因为它会抛出无效索引。

这是怎么发生的?它的目的是?

回答

0

我不知道它是否是真正的故意,但被引用的元素和COORDS只是似乎是一关:

Help on getset descriptor numpy.flatiter.coords: 

coords 
An N-dimensional tuple of current coordinates. 

Examples 
-------- 
>>> x = np.arange(6).reshape(2, 3) 
>>> fl = x.flat 
>>> fl.coords 
(0, 0) 
>>> fl.next() 
0 
>>> fl.coords 
(0, 1) 

我倾向于同意你的观点,它看起来像一个bug。

0

尽管我偶尔用x.flat来引用阵列,但我从来没有使用过或看过使用coords

In [136]: x=np.arange(6).reshape(2,3)  
In [137]: xflat = x.flat 
In [138]: for v in xflat: 
    ...:  print(v, xflat.index, xflat.coords) 
    ...:  
0 1 (0, 1) 
1 2 (0, 2) 
2 3 (1, 0) 
3 4 (1, 1) 
4 5 (1, 2) 
5 6 (2, 0) 

似乎indexcoords参考的下一个值,而不是当前的。对于第一行,当前索引为0,坐标为(0,0)。所以最后一个确实是“无端的”,并且会是迭代结束的原因。

In [155]: xflat=x.flat 
In [156]: xflat.coords, xflat.index 
Out[156]: ((0, 0), 0) 

以下是我会使用flat

In [143]: y=np.zeros((3,2)) 
In [144]: y.flat[:] = x.flat 
In [145]: y 
Out[145]: 
array([[ 0., 1.], 
     [ 2., 3.], 
     [ 4., 5.]]) 

我不会用它来进行索引迭代。

这是更好的:

In [147]: for i,v in np.ndenumerate(x): 
    ...:  print(i,v) 
    ...:  
(0, 0) 0 
(0, 1) 1 
(0, 2) 2 
(1, 0) 3 
(1, 1) 4 
(1, 2) 5 

或者一维迭代:

for i,v in enumerate(x.flat): 
    print(i,v)