2012-03-15 188 views
2

我寫了一個非常簡單的python numpy代碼。它有一個奇怪的行爲...Numpy數組賦值

from numpy import * 
# generate 2 array with 15 random int between 1 and 50 
pile = random.randint(1, 50, 15) 
pile2 = copy(pile) 

print("*** pile2",type(pile2),pile2) 
print("tab with fixed values ") 
tmp2=array([155,156,157,158,159]) 
print("tmp2",type(tmp2),tmp2) 
pile2[:5]=tmp2 
print("pile2",type(pile2),pile2) 

print("*** pile",type(pile),pile) 
print("flip a part of pile and put in an array") 
tmp=pile[4::-1] 
print("tmp",type(tmp),tmp) 
pile[:5]=tmp 
print("pile",type(pile),pile) 

當我運行該腳本,它返回:

*** pile2 <class 'numpy.ndarray'> [20 23 29 31 8 29 2 44 46 17 11 47 29 43 10] 
tab with fixed values 
tmp2 <class 'numpy.ndarray'> [155 156 157 158 159] 
pile2 <class 'numpy.ndarray'> [155 156 157 158 159 29 2 44 46 17 11 47 29 43 10] 

好! pile2成爲像 「TMP2 []和pile2 [6:]」,但對於第二...

*** pile <class 'numpy.ndarray'> [20 23 29 31 8 29 2 44 46 17 11 47 29 43 10] 
flip a part of pile and put in an array 
tmp <class 'numpy.ndarray'> [ 8 31 29 23 20] 
pile <class 'numpy.ndarray'> [ 8 31 29 31 8 29 2 44 46 17 11 47 29 43 10] 

TMP []

樁[ 31 8 29 2 44 46 17 11 47 29 43 10]

哦!分配有問題!發生什麼事 ?

+1

我無法複製此行爲。代碼中的其他地方可能存在錯誤。順便說一句,儘量避免使用'from [module] import *',因爲它可能導致與命名空間相關的問題。 – bernie 2012-03-15 16:12:27

+0

什麼版本的numpy? – milkypostman 2012-03-16 01:15:04

+0

我的Numpy版本是1.3.0。 – TristanLT 2012-03-16 08:10:46

回答

2

我可以用numpy 1.3.0來確認行爲。我想這確實是一個老bug。而這個:

pile[:5]=tmp.copy() 

解決了這個問題。

+0

好的!這解決了這個問題。我的Numpy版本是1.3.0。謝謝 – TristanLT 2012-03-16 08:17:21

0

由於tmp是樁的視圖,因此當您使用它來設置樁的內容時,它可能會導致問題。我正在使用NumPy 1.6.1,並且不能複製這個,所以也許這是在最新版本中修復的。如果你使用的是舊版本,你可以嘗試:

tmp=pile[4::-1] 
pile[:5]=tmp.copy()