在本教程中,我們將學習如何使用 Python 腳本創建淺拷貝和深拷貝。通常,我們使用=(賦值操作符)來創建 Python 對象的副本。讓我們理解與用 Python 創建副本相關的完整概念。
眾所周知,賦值運算符用於創建 Python 對象的副本,但這不是真的;它只創建目標和對象之間的綁定。當我們使用賦值操作符時,它不是創建一個新對象,而是創建一個共享舊對象引用的新變數。
當用戶希望在不修改原始對象的情況下進行更改時,副本很有幫助。用戶還喜歡創建一個副本來處理可變對象。
讓我們理解下面的例子。
示例-
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 'a']]
list2 = list1
list2[1][2] = 4
print('Old List:', list1)
print('ID of Old List:', id(list1))
print('New List:', list2)
print('ID of New List:', id(list2))
輸出:
Old List: [[1, 2, 3], [4, 5, 4], [7, 8, 'a']]
ID of Old List: 1909447368968
New List: [[1, 2, 3], [4, 5, 4], [7, 8, 'a']]
ID of New List: 1909447368968
解釋-
在上面的輸出中,我們可以看到變數 list1 和 list2 共享同一個 id 1909447368968。
如果我們對列表 1 或列表 2 中的任何值進行任何更改,更改將反映在兩者中。
主要動機是創建一個 Python 對象的副本,我們可以在不改變原始數據的情況下修改副本。在 Python 中,有兩種方法可以創建副本。
- 淺拷貝
- 深度複製
我們將使用複製模塊來創建上述副本。
拷貝模塊用於創建淺拷貝和深拷貝。讓我們看看每種方法。
淺拷貝是存儲原始元素引用的對象的拷貝。它創建新的集合對象,然後使用在原始集合中找到的子對象來佔據它。
它複製嵌套對象的引用,但不創建嵌套對象的副本。所以如果我們對複製的對象做任何修改都會反映在原始對象中。我們將使用 copy() 函數來實現它。
示例-
# importing "copy" for copy operations
import copy
# initializing list 1
list1 = [1, 7, [3,5], 8]
# using copy to shallow copy
list2 = copy.copy(list1)
# original elements of list
print ("The original elements before shallow copying")
for i in range(0,len(list1)):
print (list1[i],end=" ")
print("\r")
# adding and element to new list
list2[2][0] = 10
# checking if change is reflected
print ("The original elements after shallow copying")
for i in range(0,len( list1)):
print (list1[i],end=" ")
輸出:
The original elements before shallow copying
1 7 [3, 5] 8
The original elements after shallow copying
1 7 [10, 5] 8
在上面的代碼中,我們在列表 1 中製造了反映在另一個列表中的機會。
示例- 2
import copy
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
list2 = copy.copy(list1)
list1.append([13, 14,15])
print("Old list:", list1)
print("New list:", list2)
輸出:
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
解釋-
在上面的代碼中,我們創建了 list1 的一個淺拷貝。新創建的列表 2 包含對存儲在列表 1 中的原始嵌套對象的引用。然後,我們將[13,14,15]追加到舊列表中,並且在新列表中不複製子列表。
深度複製是我們創建一個新對象並遞歸添加複製元素的過程。我們將使用複製模塊中的 deecopy() 方法。創建原始對象及其整個對象的獨立副本。讓我們理解下面的例子。
示例-
import copy
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
z = copy.deepcopy(xs)
print(x)
prin(z)
輸出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
解釋-
在上面的輸出中,我們可以看到 z 是我們使用 deecopy() 方法創建的 x 的克隆。如果我們對其中一個子對象進行更改,不會影響原始對象。
這兩個對象在深度副本中都是完全獨立的。列表 x 被遞歸克隆,包括它的所有子對象。
import copy
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
z = copy.deepcopy(x)
x[2][2] = 'Hello'
print(x)
示例- 2:
import copy
list1 = [0, [1, 2], [3,5], 4]
# using deepcopy to deep copy
list2 = copy.deepcopy(list1)
# original elements of list
print ("The original list: ")
for i in range(0,len(list1)):
print (list1[i],end=" ")
print("\r")
# adding and element to new list
list2[1][0] = 8
# Change is reflected in l2
print ("The new list after deep copying: ")
for i in range(0,len( list1)):
print (list2[i],end=" ")
print("\r")
# Change is NOT reflected in original list
# as it is a deep copy
print ("The original elements:")
for i in range(0,len( list1)):
print (list1[i],end=" ")
輸出:
The original list:
0 [1, 2] [3, 5] 4
The new list after deep copying:
0 [8, 2] [3, 5] 4
The original elements:
0 [1, 2] [3, 5] 4
我們還可以使用複製方法複製任意 Python 對象,包括自定義類。可以使用 copy.copy() 和 copy.deepcopy() 方法複製任何對象。
讓我們理解下面的例子。
示例-
import copy
class Func_New:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Func_new(%r, %r)' % (self.x, self.y)
a = Func_New(50, 56)
b = copy.copy(a)
print(a)
print(b)
print(a is b)
print(b is a)
輸出:
Func_new(50, 56)
Func_new(50, 56)
False
False
解釋-
在上面的代碼中,我們創建了一個名為 Func_new 的用戶定義類,並定義了 repr() 來檢查對象。接下來,我們使用複製模塊創建了淺層副本。我們實例化該類,並檢查原始的和它的淺拷貝是否都是。
複合對象是淺拷貝和深拷貝的主要區別。包含其他對象(如列表或類實例)的對象稱為列表或類實例。
淺拷貝會創建一個新的複合對象,然後添加對原始對象的引用。
深度複製會創建一個新的複合對象,然後添加對原始對象的引用。
我們可以用複製模塊複製任意對象(包括自定義類)。
原創文章,作者:EBWSB,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126647.html