欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅copy与深copy举例

程序员文章站 2022-04-14 23:02:14
例1: 输出结果: 例2: 输出结果: ......

 例1: 

 1 #!/usr/bin/env python
 2 import copy
 3 d1 = {'x':1,'y':2,'z':[3,4.5]}
 4 d2 = d1
 5 d3 = d1.copy()
 6 d4 = copy.copy(d1)
 7 d5 = copy.deepcopy(d1)
 8 d1['x'] = 'm'
 9 d1['z'][0] = 9
10 print(d1)
11 print(d2)
12 print(d3)
13 print(d4)
14 print(d5)

  输出结果:

浅copy与深copy举例

 例2:

 1 #!/usr/bin/env python
 2 import copy
 3 l1 = [1,2,[3.4,5]]
 4 l2 = l1[:]
 5 l3 = l1
 6 l4 = copy.copy(l1)
 7 l5 = copy.deepcopy(l1)
 8 l1[0] = 'a'
 9 l1[2][0] = 3
10 print(l1)
11 print(l2)
12 print(l3)
13 print(l4)
14 print(l5)

 输出结果:

浅copy与深copy举例