对于浅拷贝和深拷贝的区别,这里似乎有些误解。你在你的问题中说明你是在附加列表列表。假设下面是这样一个列表:In [32]: x = [[1,2,3],[4,5,6]]
在浅拷贝中,我们只复制第一层。从文件中:A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
^{pr2}$
如果我们现在修改z的内容,我们将修改x,因为我们使用了一个浅拷贝。在In [38]: z[0][0][0]=7
In [39]: x
Out[39]: [[7, 2, 3], [4, 5, 6]]
在深度复制中,我们在所有级别复制对象,本质上是创建原始对象的克隆。从文件中:A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.In [40]: import copy
In [41]: z = []
In [42]: x = [[1,2,3],[4,5,6]]
In [43]: z.append(copy.deepcopy(x))
In [44]: z
Out[44]: [[[1, 2, 3], [4, 5, 6]]]
In [45]: z[0][0][0] = 7
In [46]: x
Out[46]: [[1, 2, 3], [4, 5, 6]]
Numpy可能是解决这个问题的最快的解决方案,但是您必须重构代码才能获得好处。如果在循环的基本级别中在列表和数组之间转换,Numpy将不会给您带来好处。相反,您应该尽早尝试将问题矢量化,并尽量减少类型转换的次数。在
编辑:
看看更新问题,似乎有一个非常简单的解决方案。如果列表中的列表只包含不可变类型,则可以使用以下任一方法:def my_copy_1(org):
return (copy.copy(org[0]),org[1],org[2])
def my_copy_2(org):
return (org[0][:],org[1],org[2])
根据您最初的实现测试这些测试的速度,我得到:In [2]: a = [[1,2,3],1,2]
In [3]: %timeit tmp.my_copy_orig(a)
100000 loops, best of 3: 2.05 µs per loop
In [4]: %timeit tmp.my_copy_1(a)
100000 loops, best of 3: 2.06 µs per loop
In [5]: %timeit tmp.my_copy_2(a)
1000000 loops, best of 3: 784 ns per loop
从速度来看,my_copy_2显然是这里的赢家。您可以测试它是否产生正确的行为:In [6]: a = [[1,2,3],1,2]
In [7]: z = tmp.my_copy_2(a)
In [8]: z[2] = 999
In [9]: z[0][0] = 999
In [10]: a
Out[10]: [[1, 2, 3], 1, 2]
In [11]: z
Out[11]: [[999, 2, 3], 1, 999]