为什么修改数组副本会影响原始副本? [英] Why does modifying copy of array affect original?

查看:56
本文介绍了为什么修改数组副本会影响原始副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,如果这是一个菜鸟问题,我很抱歉,但是我使用的是python,但是我在复制数组时遇到问题,但是当我修改副本时,它会影响原始数组.我想将边界矩阵的线性偏移量添加到一组坐标:

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

我期望的输出是xyzCoord不会受到影响,因为我进行了复制(toAdd),然后对其进行了修改.奇怪的是,此循环确实影响了我的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:

输出为:

[[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], ...


就上下文而言,我的想法是我最终希望使用转置后的值制作一个单独的列表,然后最终创建一个插值列表,但是这部分使我失望. IE.我理想地想创建: [[0.0,0.0,0.0],[5.818,0.0,0.0],[2.909,0.0,0.0],[8.727,2.909,0.0] ...] 然后为Y和Z做一个更大的循环.这样,我可以在X Y和Z中传播任意坐标,并且可以任意传播.


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的最令人惊讶的事情之一-=运算符永远不会复制任何东西!它只是将新名称附加到现有对象上.

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][:]

您还可以从 copy模块复制对象.

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

这篇关于为什么修改数组副本会影响原始副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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