python deepcopy和浅表复制并传递参考 [英] python deepcopy and shallow copy and pass reference

查看:82
本文介绍了python deepcopy和浅表复制并传递参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关python深度复制和浅表复制的问题.

A question about python deepcopy and shallow copy.

位于的帖子 深层副本之间的区别是什么和浅表副本?

不能帮我.

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

why e.g. 1 's sum is 6 not 10 ?

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

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

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.

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,如果theCopy是对kvps的引用,则应为10.

its sum is 6 , if theCopy is a reference to kvps , it should be 10.

推荐答案

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

Shallow copy makes a copy of mutable objects in the top-level container. A deep copy makes a new instance of all mutable containers in the data structure.

例如2"的结果为10,因为您将字典复制到外部,但是内部的两个列表仍然是旧列表,并且列表可以就地更改(它们是可变的).

"e.g. 2" results in 10 because you copy the dict on the outside, but the two lists inside are still the old lists, and lists can be changed in-place (they're mutable).

深层复制使aList.copy(),bList.copy()运行,并将字典中的值替换为其副本.

Deep copy makes runs aList.copy(), bList.copy() and replaces the values in your dict with their copies.

例如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}

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

The list objects in both dicts are the same objects, so modifying one of the lists will be reflected in both dicts.

进行深层复制(例如3个)会导致以下结果:

Doing a deep copy (e.g. 3) results in this:

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

这意味着两个字典的内容完全不同,修改一个字典不会修改另一个字典.

This means both dicts have entirely different contents, and modifying one won't modify the other.

例如通过dict()的4等同于浅表副本.

e.g. 4 via dict() is equivalent to a shallow copy.

这篇关于python deepcopy和浅表复制并传递参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆