我有这个功能:
def change_position(old_particles):
inc_r=0.5
inc_angle=0.5
N=len(old_particles)
particlesx=old_particles
a=random.randint(0,N-1)
b=random.randint(0,1)
max_angle=np.pi*2
c=random.randint(0,1)
print 'old_particles before change', old_particles
print 'new before change', particlesx
if b==1:
if c==1:
particlesx[a][b]=particlesx[a][b]+inc_angle
if particlesx[a][b]>max_angle:
particlesx[a][b]=particlesx[a][b]-max_angle
print 'cambiamos particula',a, particlesx[a][b]
if b==1:
if c==0:
particlesx[a][b]=particlesx[a][b]-inc_angle
if particlesx[a][b]<0:
particlesx[a][b]=particlesx[a][b]+max_angle
print 'cambiamos',a, particlesx[a][b]
if b==0:
if c==0:
particlesx[a][b]=particlesx[a][b]+inc_r
if particlesx[a][b]>1:
particlesx[a][b]=particlesx[a][b]-inc_r
print 'cambiamos',a, particlesx[a][b]
if b==0:
if c==1:
particlesx[a][b]=particlesx[a][b]-inc_r
if particlesx[a][b]<0:
particlesx[a][b]=particlesx[a][b]+inc_r
print 'cambiamos',a, particlesx[a][b]
print'after change', particlesx
print'old_particles after change', old_particles
return particlesx, a
问题在于,由于我不理解的原因,函数不仅改变'particlesx'的值而且改变old_particles的值,因此脚本末尾的两个数组的值不仅在功能,但也在功能之外。谁能帮我这个? 谢谢!
答案 0 :(得分:2)
以下内容:
particlesx=old_particles
不会复制列表。相反,它使particlesx
和old_particles
都引用相同的列表。当你改变一个时,它们都会改变。
要使两者相互独立,您需要复制一份:
import copy
...
particlesx = copy.deepcopy(old_particles)