1. 程式人生 > >Python深淺copy

Python深淺copy

view style nbsp enum pytho lose pri 技術 clas

技術分享圖片
1 l1 = [1, 2, 3]
2 l2 = l1
3 l1.append(a)
4 print(l1, l2)       # 深cpoy
5 
6 l1 = [1, 2, 3]
7 l2 = l1.copy()      # 淺拷貝
8 l2.append(a)
9 print(l1, l2)
View Code

1.其他代碼

技術分享圖片
 1 # 賦值運算
 2 # l1 = [1,2,3]
 3 # l2 = l1
 4 # l1.append(‘a‘)
 5 # print(l1,l2)
 6 
 7 #copy
 8 # l1 = [1,2,3]
 9 # l2 = l1.copy()
10 # print(l1,l2) 11 # print(id(l1),id(l2)) 12 # l2.append(‘a‘) 13 # print(l1,l2) 14 15 # l1 = [1,2,[4,5,6],3] 16 # l2 = l1.copy() 17 18 # print(l1,id(l1)) 19 # print(l2,id(l2)) 20 # l1.append(‘a‘) 21 # print(l1,l2) 22 # l1[2].append(‘a‘) 23 # print(l1,l2) 24 # print(id(l1[2])) 25 # print(id(l2[2]))
26 import copy 27 # l1 = [1,2,[4,5,6],3] 28 # l2 = copy.deepcopy(l1) 29 # print(l1,id(l1)) 30 # print(l2,id(l2)) 31 # l1[2].append(‘a‘) 32 # print(l1,l2) 33 34 # l1 = [1,[1],2,3,4] 35 # l2 = l1[:] 36 # l1[1].append(‘a‘) 37 #l2 的結果是什麽? 38 39 40 # print(l1,id(l1)) 41 # print(l2,id(l2)) 42 # print(l1[1] is l2[1])
43 44 # li = [‘alex‘,‘taibai‘,‘wusir‘,‘egon‘] 45 # for i in li: 46 # print(li.index(i),i) 47 48 # for index,i in enumerate(li,1): 49 # print(index,i)
View Code

Python深淺copy