2017-02-09 46 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)