Python-深浅拷贝

一、拷贝

  对数据的复制

  1、基本数据的赋值涉及的变量内存地址变化:

1 a = [1,2,3,[2,3]]
2 b = a
3 b[3][1] = 22
4 print(a)
5 pring(b)
6 #此时,a和b指向的是同一个内存地址,所以修改其中一个,另一个也会改变

  2、浅拷贝:只复制数据的第一层

 1 a = [1,2,[3,4]]
 2 b = a.copy() # b = a[:]
 3 
 4 b[1] = 22
 5 b[2][1] = 44
 6 
 7 print(a)
 8 print(b)
 9 
10 ------->
11 
12 [1, 2, [3, 44]]
13 [1, 22, [3, 44]]

    如图:

  3、深拷贝:就是完全克隆一份,需要模块copy支持

示例:

 1 信用卡的案例:
 2 
 3 import copy
 4 
 5 husband = ['jack',123,[1500,9000]] # 名字,卡号,信用额度,余额
 6 
 7 wife = husband.copy() # wife = copy.copy(husband) 一样的也是浅拷贝
 8 wife[0] = 'lucy'
 9 wife[1] = 234
10 
11 wife[2][1] -= 8000
12 
13 print(husband,wife) #['jack', 123, [1500, 1000]] ['lucy', 234, [1500, 1000]]
14 
15 
16 husband = ['jack',123,[1500,9000]]
17 xiaosan = copy.deepcopy(husband) #深拷贝
18 xiaosan[0] = 'lilei'
19 xiaosan[1] = 345
20 xiaosan[2][1] -= 2000
21 print(husband,xiaosan) ['jack', 123, [1500, 9000]] ['lilei', 345, [1500, 7000]]

 

 了解更多查看:http://www.cnblogs.com/yuanchenqi/articles/5782764.html

 

 

 

 

 

    

posted @ 2018-03-29 10:44  JerryZao  阅读(270)  评论(0编辑  收藏  举报