擅长:python、mysql、java
<p>从<a href="https://docs.python.org/3/library/copy.html" rel="noreferrer">^{<cd1>}</a>模块的文档中:</p>
<blockquote>
<p>The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):</p>
<ul>
<li>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.</li>
<li>A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.</li>
</ul>
</blockquote>
<p>当您调用regular<code>copy.copy()</code>时,您正在执行一个浅拷贝。这意味着在列表列表的情况下,您将获得外部列表的新副本,但它将包含原始的内部列表作为其元素。相反,您应该使用<code>copy.deepcopy()</code>,这将创建外部和内部列表的新副本。</p>
<p>在第一个使用<code>copy([1,2])</code>的示例中没有注意到这一点的原因是<code>int</code>这样的原语是不可变的,因此不创建新实例就不可能更改它们的值。如果列表的内容是可变对象(如列表,或任何具有可变成员的用户定义对象),则在列表的两个副本中都会看到这些对象的任何变化。</p>