Numpy数组赋值

时间:2012-03-15 16:01:43

标签: python arrays numpy

我写了一个非常简单的python 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 [ 8 31 29 23 20 ]

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

哦!分配有问题!会发生什么事?

2 个答案:

答案 0 :(得分:2)

我可以用numpy 1.3.0确认行为。我想这确实是一个老bug。这个:

pile[:5]=tmp.copy() 

解决了这个问题。

答案 1 :(得分:0)

因为tmp是桩的视图,当你用它来设置桩的内容时它会引起问题。我正在使用NumPy 1.6.1,并且不能复制它,所以也许这是在最新版本中修复的。如果您使用的是旧版本,可以尝试:

tmp=pile[4::-1]
pile[:5]=tmp.copy()
相关问题