蟒蛇在列表中的附加元件改变它的原始变量的变化 [英] Python The appended element in the list changes as its original variable changes

查看:86
本文介绍了蟒蛇在列表中的附加元件改变它的原始变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里是什么我想在Python做抽象code。

So here's the abstract code of what I'm trying to do in python.

list_ = []
dict_ = {}
for i in range(something):
    get_values_into_dict(dict_)
    list_.append(dict_)
    dict_.clear()
print list_

下面当我清除dict_,显然都在list_的元素被删除,因为他们只是地址映射到变量dict_。

Here when I clear the dict_, obviously the all the elements in the list_ are deleted as they're just address mapped to the variable dict_.

什么,我要的是复制dict_的实例,这样我可以把它存储在list_。

What, I want is to copy the instance of dict_ so that I can store it in the list_.

有人可以解释我的方式存储在每个环路进入list_获得的字典?先谢谢了。

Can someone explain me a way to store the obtained dict in every loop into the list_? Thanks in advance.

推荐答案

您添加到字典的引用到您的列表,然后清除字典中的本身的。这消除了字典的内容,因此该字典的所有引用将表明,它现在是空的。

You are adding a reference to the dictionary to your list, then clear the dictionary itself. That removes the contents of the dictionary, so all references to that dictionary will show that it is now empty.

相比之下,与创建两个变量指向同一个字典:

Compare that with creating two variables that point to the same dictionary:

>>> a = {'foo': 'bar'}
>>> b = a
>>> b
{'foo': 'bar'}
>>> a.clear()
>>> b
{}

字典是可变的;您更改对象本身。

Dictionaries are mutable; you change the object itself.

创建一个新的字典中的循环,而不是清算和重用之一:

Create a new dictionary in the loop instead of clearing and reusing one:

list_ = []
for i in range(something):
    dict_ = {}
    get_values_into_dict(dict_)
    list_.append(dict_)
print list_

或者更好的是,有 get_values​​_into_dict()返回的字典来代替:

list_ = []
for i in range(something):
    dict_ = return_values_as_dict()
    list_.append(dict_)
print list_

这篇关于蟒蛇在列表中的附加元件改变它的原始变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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