理解 dict.copy() - 浅还是深? [英] Understanding dict.copy() - shallow or deep?

查看:30
本文介绍了理解 dict.copy() - 浅还是深?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 dict.copy() 的文档时,它说它制作了字典的浅拷贝.我正在关注的书(Beazley 的 Python 参考)也是如此,其中说:

<块引用>

m.copy() 方法使一个浅层包含在一个项目的副本映射对象并将它们放在一个新的映射对象.

考虑一下:

<预><代码>>>>原始 = dict(a=1, b=2)>>>new = original.copy()>>>new.update({'c': 3})>>>原来的{'a':1,'b':2}>>>新的{'a':1,'c':3,'b':2}

所以我假设这会更新 original 的值(并添加 'c': 3),因为我正在做一个浅拷贝.就像你为一个列表做的一样:

<预><代码>>>>原始 = [1, 2, 3]>>>新 = 原始>>>new.append(4)>>>新的,原始的([1, 2, 3, 4], [1, 2, 3, 4])

这按预期工作.

既然两者都是浅拷贝,为什么 dict.copy() 不能像我期望的那样工作?还是我对浅拷贝和深拷贝的理解有问题?

解决方案

浅拷贝"意味着字典的内容不是按值复制的,而只是创建一个新的引用.

<预><代码>>>>a = {1: [1,2,3]}>>>b = a.copy()>>>一、乙({1: [1, 2, 3]}, {1: [1, 2, 3]})>>>a[1].append(4)>>>一、乙({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

相比之下,深拷贝将按值复制所有内容.

<预><代码>>>>导入副本>>>c = copy.deepcopy(a)>>>一、三({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})>>>a[1].append(5)>>>一、三({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})

所以:

  1. b = a:引用赋值,使ab指向同一个对象.

  2. b = a.copy():浅拷贝,ab会成为两个孤立的对象,但它们的内容仍然共享相同的参考

  3. b = copy.deepcopy(a):深度复制,ab的结构和内容变得完全隔离.

While reading up the documentation for dict.copy(), it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:

The m.copy() method makes a shallow copy of the items contained in a mapping object and places them in a new mapping object.

Consider this:

>>> original = dict(a=1, b=2)
>>> new = original.copy()
>>> new.update({'c': 3})
>>> original
{'a': 1, 'b': 2}
>>> new
{'a': 1, 'c': 3, 'b': 2}

So I assumed this would update the value of original (and add 'c': 3) also since I was doing a shallow copy. Like if you do it for a list:

>>> original = [1, 2, 3]
>>> new = original
>>> new.append(4)
>>> new, original
([1, 2, 3, 4], [1, 2, 3, 4])

This works as expected.

Since both are shallow copies, why is that the dict.copy() doesn't work as I expect it to? Or my understanding of shallow vs deep copying is flawed?

解决方案

By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.

>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

In contrast, a deep copy will copy all contents by value.

>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})

So:

  1. b = a: Reference assignment, Make a and b points to the same object.

  2. b = a.copy(): Shallow copying, a and b will become two isolated objects, but their contents still share the same reference

  3. b = copy.deepcopy(a): Deep copying, a and b's structure and content become completely isolated.

这篇关于理解 dict.copy() - 浅还是深?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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