编程语言
首页 > 编程语言> > python deepcopy和浅拷贝和传递引用

python deepcopy和浅拷贝和传递引用

作者:互联网

关于python深度复制和浅拷贝的问题.

帖子在
What is the difference between a deep copy and a shallow copy?

无法帮助我.

为什么1的总和是6而不是10?

例如:1

kvps = { '1' : 1, '2' : 2 }
theCopy = kvps.copy()  # both point to the same mem location ? 
kvps['1'] = 5
sum = kvps['1'] + theCopy['1']
print sum

输出和是6

例如:2:

aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }

theCopy = kvps.copy()  # both point to the same mem location ? 
kvps['1'][0] = 5
sum = kvps['1'][0] + theCopy['1'][0]

print sum

输出总和是10

例如:3

import copy

aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }

theCopy = copy.deepcopy(kvps)
kvps['1'][0] = 5
sum = kvps['1'][0] + theCopy['1'][0]

print sum

输出和是6.

另外,例如, 4

kvps = { '1' : 1, '2' : 2 }    
theCopy = dict(kvps)  #  theCopy hold a reference to kvps ?     
kvps['1'] = 5  # should also change theCopy , right ?    
sum = kvps['1'] + theCopy['1']    
print kvps    
print theCopy    
print sum

它的总和是6,如果复制是对kvps的引用,它应该是10.

解决方法:

浅拷贝在顶级容器中创建可变对象的副本.深层复制在数据结构中创建所有可变容器的新实例.

“例如2”导致10,因为你在外面复制了dict,但是里面的两个列表仍然是旧列表,并且列表可以就地更改(它们是可变的).

深层复制使运行aList.copy(),bList.copy()并用它们的副本替换dict中的值.

例如1解释:

kvps = {'1': 1, '2': 2}
theCopy = kvps.copy()

# the above is equivalent to:
kvps = {'1': 1, '2': 2}
theCopy = {'1': 1, '2': 2}

当你将其应用于例如2:

kvps = {'1': aList, '2': bList}
theCopy = {'1': aList, '2': bList}

两个dicts中的列表对象是相同的对象,因此修改其中一个列表将反映在两个dicts中.

执行深层复制(例如3)会导致:

kvps = {'1': aList, '2': bList}
theCopy = {'1': [1, 2], '2': [3, 4]}

这意味着两个dicts具有完全不同的内容,并且修改一个不会修改另一个.

例如4通过dict()相当于浅拷贝.

标签:shallow-copy,python,linux,deep-copy,reference
来源: https://codeday.me/bug/20191008/1873576.html