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

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

问题描述

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

<预><代码>>>>>>>a = []>>>b = {1:'一个'}>>>a.附加(b)>>>一种[{1: '一个'}]>>>b[1] = '一个'>>>一种[{1:'一个'}]>>>

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

我不希望更改反映在列表中.我该怎么做?

感谢您的宝贵时间!

解决方案

您是对的,因为您的列表包含对原始词典的引用.

a.append(b.copy()) 应该可以解决问题.

请记住,这是一个浅拷贝.另一种方法是使用 copy.deepcopy(b),这是一个深拷贝.

I tried the following in the python interpreter:

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

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?

Thank you for your time!

解决方案

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

a.append(b.copy()) should do the trick.

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天全站免登陆