Python直接赋值、浅拷贝和深度拷贝解析

2018-07-30  本文已影响12人  默写年华Antifragile
  1. 实例:
# -*- coding: UTF-8 -*-                                          
import copy
a = {1:[1,2,3]}
b = a 
c = a.copy()
d = copy.deepcopy(a)
print "a=",a
print "b=a:",b
print "c=a.copy():",c
print "d=a.deepcopy():",d
print

a[1].append(4)
print "a=",a
print "b=a:",b
print "c=a.copy():",c
print "d=a.deepcopy():",d
print

a[2]='xyz'

print "a=",a
print "b=a:",b
print "c=a.copy():",c
print "d=a.deepcopy():",d
print

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
a= {1: [1, 2, 3]}
b=a: {1: [1, 2, 3]}
c=a.copy(): {1: [1, 2, 3]}
d=a.deepcopy(): {1: [1, 2, 3]}

a= {1: [1, 2, 3, 4]}
b=a: {1: [1, 2, 3, 4]}
c=a.copy(): {1: [1, 2, 3, 4]}
d=a.deepcopy(): {1: [1, 2, 3]}

a= {1: [1, 2, 3, 4], 2: 'xyz'}
b=a: {1: [1, 2, 3, 4], 2: 'xyz'}
c=a.copy(): {1: [1, 2, 3, 4]}
d=a.deepcopy(): {1: [1, 2, 3]}

解析:

参考:http://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

上一篇 下一篇

猜你喜欢

热点阅读