共計 1509 個字符,預計需要花費 4 分鐘才能閱讀完成。
今天就跟大家聊聊有關如何進行 python 列表中的賦值與深淺拷貝,可能很多人都不太了解,為了讓大家更加了解,丸趣 TV 小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
首先創建一個列表
a=[[1,2,3],4,5,6]
一、賦值
a=[[1,2,3],4,5,6]b=aa[0][1]= tom print(a)print(b) 結果:
[[1, tom , 3], 4, 5, 6]
[[1, tom , 3], 4, 5, 6]
a=[[1,2,3],4,5,6]b=ab[0][1]= tom print(a)print(b) 結果:[[1, tom , 3], 4, 5,
6][[1, tom , 3], 4, 5,
6] 總結:賦值不管是對 a 列表改變還是對 b 列表改變,只要改變其中一個,另一個也會跟著變,這是因為 a 和 b 共用一塊內存,沒有創建新的內存,他們是相同的,他們指向同一個內存區域。二、淺拷貝
[:]or copy()
a=[[1,2,3],4,5,6]b=a.copy()b[0][1]= tom print(a)print(b) 結果:
[[1, tom , 3], 4, 5, 6]
[[1, tom , 3], 4, 5, 6]
a=[[1,2,3],4,5,6]b=a.copy()a[0][1]= tom print(a)print(b) 結果:[[1, tom , 3],
4, 5, 6][[1, tom , 3], 4, 5, 6]
a=[[1,2,3],4,5,6]b=a.copy()b[1]= tom print(a)print(b) 結果:
[[1, 2, 3], 4, 5, 6]
[[1, 2, 3], tom , 5, 6]
a=[[1,2,3],4,5,6]b=a.copy()a[1]= tom print(a)print(b) 結果:
[[1, 2, 3], tom , 5, 6]
[[1, 2, 3], 4, 5, 6]
總結:從上面代碼可以看出來淺拷貝是重新開辟一塊內存,拷貝第一層數據,不拷貝內部子元素
在本代碼中,b 列表重新開辟了一塊內存放元素【b【0】,4,5,6】,也就是第一層內容,
然后 b【0】的位置指向了 a【0】指向的內存位置
三、深拷貝 使用 copy 函數
重新開辟一塊內存,存放拷貝列表的所有內容。a 集合與 b 集合互不影響
import
copya=[[1,2,3],4,5,6]b=copy.deepcopy(a)a[1]= tom print(a)print(b) 結果:
[[1, 2, 3], tom , 5, 6]
[[1, 2, 3], 4, 5, 6]
import
copya=[[1,2,3],4,5,6]b=copy.deepcopy(a)b[1]= tom print(a)print(b) 結果:
[[1, 2, 3], 4, 5, 6]
[[1, 2, 3], tom , 5, 6]
import
copya=[[1,2,3],4,5,6]b=copy.deepcopy(a)b[0][1]= tom print(a)print(b) 結果;
[[1, 2, 3], 4, 5, 6]
[[1, tom , 3], 4, 5, 6]
import
copya=[[1,2,3],4,5,6]b=copy.deepcopy(a)a[0][1]= tom print(a)print(b) 結果:
[[1, tom , 3], 4, 5, 6]
[[1, 2, 3], 4, 5, 6]
copy 函數也可以淺拷貝:
import
copya=[[1,2,3],4,5,6]b=copy.copy(a)a[0][1]= tom print(a)print(b) 結果:
[[1, tom , 3], 4, 5, 6]
[[1, tom , 3], 4, 5, 6]
看完上述內容,你們對如何進行 python 列表中的賦值與深淺拷貝有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注丸趣 TV 行業資訊頻道,感謝大家的支持。