问题
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 is a vector object.)
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}]
(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.
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?
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
回答1:
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
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))
来源:https://stackoverflow.com/questions/18239705/modifying-one-object-in-list-modifies-all-objects-in-list