Why does modifying copy of array affect original?

2020-02-11 07:50发布

Hi everyone I am sorry if this is a noob question but I am using python and I have an issue where I copy an array but then when I modify the copy it affects the original. I want to add a linear offset from the boundaries matrix to a set of coordinates:

boundaries = [[5.818, 0.0, 0.0], [0.0, 5.818, 0.0], [0.0, 0.0, 5.818]]

xyzCoord = [[0.0, 0.0, 0.0], [2.909, 2.909, 0.0], ...

extraX=[]
for i in range(0,len(xyzCoord)):
    toAdd=[]
    toAdd=xyzCoord[i]
    toAdd[0]=toAdd[0]+boundaries[0][0]

print xyzCoord

The output I expect is that xyzCoord should not be affected because I make a duplicate (toAdd) and then modify that. Strangely enough this loop does affect my xyzCoord:

The output is:

[[5.818, 0.0, 0.0], [0.0, 5.818, 0.0], [0.0, 0.0, 5.818]]

[[0.0, 0.0, 0.0], [2.909, 2.909, 0.0], ...

[[5.818, 0.0, 0.0], [8.727, 2.909, 0.0], ...

EDIT: For context, the idea is that I want to eventually make a separate list with the transposed values and then ultimately create an intercalated list but this part is holding me up. I.e. I would ideally like to create: [[0.0, 0.0, 0.0], [5.818, 0.0, 0.0], [2.909, 0.0, 0.0], [8.727, 2.909, 0.0]...] and then make a larger loop for Y and Z. This way I could propagate some coordinates in the X Y and Z and arbitrary number of times.

标签: python list
3条回答
祖国的老花朵
2楼-- · 2020-02-11 08:29

This is one of the most surprising things about Python - the = operator never makes a copy of anything! It simply attaches a new name to an existing object.

If you want to make a copy of a list, you can use a slice of the list; the slicing operator does make a copy.

toAdd=xyzCoord[i][:]

You can also use copy or deepcopy from the copy module to make a copy of an object.

查看更多
Explosion°爆炸
3楼-- · 2020-02-11 08:36

Because your using an array of arrays (list of lists) the inner list is an object so you are only copying the reference of the inner object instead of copying the values.

查看更多
Viruses.
4楼-- · 2020-02-11 08:45

toAdd is not a duplicate. The following makes toAdd refer to the same sub-list as xyzCoord[i]:

toAdd = xyzCoord[i]

When you change elements of toAdd, the corresponding elements of xyzCoord[i] also change.

Instead of the above, write:

toAdd = xyzCoord[i][:]

This will make a (shallow) copy.

查看更多
登录 后发表回答