本文介绍了通过列表乘法创建的嵌套引用列表的Deepcopy不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我很喜欢Python,但是参考和Deepcopy有时会吓到我.

As much as I love Python, the reference and deepcopy stuff sometimes freaks me out.

为什么Deepcopy在这里不起作用:

Why does deepcopy not work here:

>>> import copy
>>> a = 2*[2*[0]]
>>> a
[[0, 0], [0, 0]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 1
>>> b
[[1, 0], [1, 0]]     #should be: [[1, 0], [0, 1]]
>>> 

我正在使用一个numpy数组作为工作区,无论如何我以后都需要.但是我确实希望,如果我使用Deepcopy,就不必再追逐任何无用的引用了.还有其他无法使用的陷阱吗?

I am using a numpy array as a workarround which I need later on anyway. But I really had hoped that if I used deepcopy I would not have to chase any unintended references any more. Are there any more traps where it does not work?

推荐答案

它不起作用,因为您正在创建一个包含两个对同一数组的引用的数组.

It doesn't work because you are creating an array with two references to the same array.

另一种方法是:

[[0]*2 for i in range(2)]

或更明确的是:

[[0 for j in range(2)] for i in range(2)]

之所以行之有效,是因为它在每次迭代时都会创建一个新的数组.

This works because it creates a new array on each iteration.

每当您有一个包含引用的数组时,都应该小心.例如,[Foo()] * 2[Foo() for i in range(2)]不同.在第一种情况下,仅构造一个对象,并且数组包含对该对象的两个引用.在第二种情况下,将构造两个单独的对象.

Any time you have an array containing references you should be careful. For example [Foo()] * 2 is not the same as [Foo() for i in range(2)]. In the first case only one object is constructed and the array contains two references to it. In the second case, two separate objects are constructed.

这篇关于通过列表乘法创建的嵌套引用列表的Deepcopy不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:09