功能看起來像:
def mutate_color(tri):
out = tri.copy()
out[3][np.random.randint(3)] = np.random.randint(256)
return out
一個物件看起來像:
TRI_A = array([array([181, 75]), array([99, 9]), array([53, 15]),
array([18, 5, 19], dtype=uint8)], dtype=object)
<== 這是一個彩色三角形,前三個是坐標,最后一個是RGB值。
但是當我將這個(或類似這樣的物件)傳遞給這個函式時:
例如:
TRI_B = mutate_color(TRI_A)
我注意到 TRI-B 和 TRI_A 都被修改了,我的意思是我使用 .copy() 函式,TRI_A 不應該與原始檔案保持相同而只有 B 會被修改嗎?
請幫忙。
uj5u.com熱心網友回復:
的資料型別TRI_A是object,因此實際存盤在陣列中的值是指向各種物件的指標(在這種情況下,是幾個不同的 numpy 陣列)。當該copy()方法創建一個新object陣列時,它只復制指標。它不會遞回復制 numpy 陣列指向的所有 Python 物件。
這在 .doc 的檔案字串中有進一步的解釋numpy.copy。特別是,
Note that np.copy is a shallow copy and will not copy object
elements within arrays. This is mainly important for arrays
containing Python objects. The new array will contain the
same object which may lead to surprises if that object can
be modified (is mutable):
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = np.copy(a)
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)
To ensure all elements within an ``object`` array are copied,
use `copy.deepcopy`:
>>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> c[2][0] = 10
>>> c
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369818.html
