修改列表中的一个对象会修改列表中的所有对象 [英] Modifying one object in list modifies all objects in list

查看:70
本文介绍了修改列表中的一个对象会修改列表中的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在3d网格中直接与任何给定点相邻的坐标列表.例如,当给定向量{3,3,3}时,该函数应返回以下列表:

I am trying to make a list of coordinates directly adjacent to any given point in a 3d grid. For example, when given a vector {3,3,3}, the function should return the following list:

[{4,3,3},{2,3,3},{3,4,3},{3,2,3},{3,3,4},{3,3,2}]

(花括号中的值是矢量对象,而不是列表.)这是我的代码:

(The values in curly braces are vector objects, not lists.) Here is my code:

def touchingBlocks(sourceBlock):
    touching = []
    for t in range(6):
        touching.append(sourceBlock)
    touching[0].x += 1
    touching[1].x -= 1
    touching[2].y += 1
    touching[3].y -= 1
    touching[4].z += 1
    touching[5].z -= 1
    return touching

(sourceBlock是矢量对象.)

(sourceBlock is a vector object.)

但是,当我尝试修改列表中的任何一个对象时,它都会修改每个对象.例如,在touching [0] .x + = 1命令之后,我希望touching等于:

When I try to modify any one of the objects in the list though, it modifies every object. For example, after the touching[0].x += 1 command, I would expect touching to be equal to:

[{4,3,3},{3,3,3},{3,3,3},{3,3,3},{3,3,3},{3,3,3}]

(假设我们给了函数向量{3,3,3})相反,每个对象的"x"值都发生了变化,而不仅仅是第一个.在函数结束时,此错误导致仅返回原始向量的六个副本的列表.

(Assuming we gave the function the vector {3,3,3}) Instead, the 'x' value of every object got changed, instead of only the first. By the end of the function, this error results in simply returning a list of six copies of the original vector.

我认为这可能是因为列表中的对象只是指向相同版本的sourceBlock的指针,尽管我不确定.您可以确认我是否正确以及如何解决此问题吗?

I think this might be because the objects in the list are just pointers to the same version of sourceBlock, though I am not sure. Can you confirm if I am right and how to fix this?

此外,这是指向矢量对象的链接,以防您需要在其中查看: https://www.dropbox.com/s/zpuo6473z225la7/vec3.py

Also, here is the link to the vector object, in case you need to look in there: https://www.dropbox.com/s/zpuo6473z225la7/vec3.py

推荐答案

def touchingBlocks(sourceBlock):
    touching = []
    for t in range(6):
        touching.append(sourceBlock)  # Here is your error
    touching[0].x += 1
    touching[1].x -= 1
    touching[2].y += 1
    touching[3].y -= 1
    touching[4].z += 1
    touching[5].z -= 1
    return touching

您将同一对象添加6次.每次编辑一个对象时,您都可以编辑商场.您应该使用 copy.depcopy 创建对象的副本.(deepcopy也将复制嵌套对象,而不仅仅是它们的引用)

You are adding the same object 6 times. Everytime you edit one object, you edit them all. You should create copies of your obect using copy.depcopy (deepcopy will copy the nested objects as well, not just their reference)

import copy
[...code...]
touching.append(copy.deepcopy(sourceBlock))

这篇关于修改列表中的一个对象会修改列表中的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆