【问题标题】:python: my function change the argument for no reasonpython:我的函数无缘无故改变了参数
【发布时间】:2013-04-07 16:07:30
【问题描述】:

我有这个功能:

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 的值,因此脚本末尾的两个数组的值不仅在功能之外还有功能。谁能帮我这个? 谢谢!

【问题讨论】:

    标签: python arrays function global


    【解决方案1】:

    以下内容:

    particlesx=old_particles
    

    不制作列表的副本。相反,它使particlesx 和old_particles 都引用同一个列表。当你改变一个时,它们都会改变。

    要使两者相互独立,您需要制作一个副本:

    import copy
    ...
    particlesx = copy.deepcopy(old_particles)
    

    【讨论】:

    • 例如:如果你类中的元素是不可变的,你也可以使用语法 new_p = old_p[:]
    • @Ant:在这里,它们不是(元素本身似乎是列表)。因此我建议使用deepcopy()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    相关资源
    最近更新 更多