<p>你需要一份复印件:</p>
<pre><code>b = a.copy()
</code></pre>
<p><code>b = a</code>创建一个引用,因此<code>a is b</code>它们都指向内存中的相同位置,<code>a.copy()</code>实际上创建了一个新对象。在</p>
^{pr2}$
<p>如果使用<a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing" rel="nofollow">basic slicing</a>对数组进行切片,则id将不同,但任何更改都将反映在a和b中,因为使用基本索引时,基本切片生成的所有数组始终是原始数组的视图。</em>A<a href="http://docs.scipy.org/doc/numpy/glossary.html#term-view" rel="nofollow">view</a>是一个数组,它不拥有自己的数据,而是引用另一个数组的数据。</em>所以视图是一个新对象,但内容仍然属于原始数组。在</p>
<p>但是,使用<a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">advanced indexing</a><em>高级索引总是返回数据的副本</em></p>
<pre><code>In [141]: a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [142]: b = a[1:7:2] # basic indexing/view
In [143]: id(a)
Out[143]: 140335437385856
In [144]: id(b)
Out[144]: 140335437356528
In [145]: b[0] = 999
In [146]: a
Out[146]: array([ 0, 999, 2, 3, 4, 5, 6, 7, 8, 9])
In [148]: b
Out[148]: array([999, 3, 5])
In [149]: a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [150]: b = a[[0,3,5]] # advanced indexing/copy
In [151]: b
Out[151]: array([0, 3, 5])
In [152]: b[0] = 999
In [153]: a
Out[153]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [154]: b
Out[154]: array([999, 3, 5])
In [157]: a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [158]: b = a[a] # copy
In [159]: b
Out[159]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [160]: b[0] = 99
In [161]: a
Out[161]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [162]: b
Out[162]: array([99, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>这是特定的numpy行为,切片一个常规python平面列表将始终创建一个新列表,其中a中的更改不会反映在b中</p>
<pre><code>In [190]: a = [1,2,3,4,5]
In [191]: b = a[:3]
In [192]: b[0] = 999
In [193]: a
Out[193]: [1, 2, 3, 4, 5]
In [194]: b
Out[194]: [999, 2, 3]
</code></pre>
<p>如果python列表包含子列表,并且您创建了一个浅拷贝,那么您将捕获python列表:</p>
<pre><code>In [197]: a = [[1,2,3],[4,5]]
In [198]: b = a[:]
In [199]: id(a)
Out[199]: 140335437468296
In [200]: id(b)
Out[200]: 140335437417992
In [201]: b[0][0] = 999
In [202]: b
Out[202]: [[999, 2, 3], [4, 5]]
In [203]: a
Out[203]: [[999, 2, 3], [4, 5]]
</code></pre>
<p>您需要制作一个<a href="https://docs.python.org/2/library/copy.html#copy.deepcopy" rel="nofollow">copy.deepcopy</a>:</p>
<pre><code>In [204]: a = [[1,2,3],[4,5]]
In [205]: from copy import deepcopy
In [206]: b = deepcopy(a)
In [207]: b[0][0] = 999
In [208]: b
Out[208]: [[999, 2, 3], [4, 5]]
In [209]: a
Out[209]: [[1, 2, 3], [4, 5]]
</code></pre>