我寫了一個非常簡單的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]
哦!分配有問題!發生什麼事 ?
我無法複製此行爲。代碼中的其他地方可能存在錯誤。順便說一句,儘量避免使用'from [module] import *',因爲它可能導致與命名空間相關的問題。 – bernie 2012-03-15 16:12:27
什麼版本的numpy? – milkypostman 2012-03-16 01:15:04
我的Numpy版本是1.3.0。 – TristanLT 2012-03-16 08:10:46