python:将字典附加到列表 - 我看到一个像行为的指针 [英] python: Appending a dictionary to a list - I see a pointer like behavior

查看:133
本文介绍了python:将字典附加到列表 - 我看到一个像行为的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python解释器中尝试过以下内容:

I tried the following in the python interpreter:

>>>
>>> a = []
>>> b = {1:'one'}
>>> a.append(b)
>>> a
[{1: 'one'}]
>>> b[1] = 'ONE'
>>> a
[{1: 'ONE'}]
>>>

这里,在将字典b附加到列表a之后,我正在更改与字典'a'中的键1对应的值。不知怎的,这个变化也反映在列表中。当我将一个字典附加到列表中时,我不只是附加字典的值吗?看起来好像我附加了一个指向列表的字典的指针,因此字典的更改也被反映在列表中。

Here, after appending the dictionary 'b' to the list 'a', I'm changing the value corresponding to the key 1 in dictionary 'a'. Somehow this change gets reflected in the list too. When I append a dictionary to a list, am I not just appending the value of dictionary? It looks as if I have appended a pointer to the dictionary to the list and hence the changes to the dictionary are getting reflected in the list too.

我不想要更改以反映在列表中。如何做?

I do not want the change to get reflected in the list. How do I do it?

谢谢你的时间!

推荐答案

p>您是正确的,因为您的列表包含原始字典的引用

You are correct in that your list contains a reference to the original dictionary.

a.append(b .copy())应该做的伎俩。

请记住,这是一个浅的副本。另一种方法是使用 copy.deepcopy(b) ,这是一个深层次的副本。

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

这篇关于python:将字典附加到列表 - 我看到一个像行为的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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