简体   繁体   English

Python随着原始变量的更改,列表中的附加元素也会更改

[英]Python The appended element in the list changes as its original variable changes

So here's the abstract code of what I'm trying to do in python. 所以这是我在python中尝试做的抽象代码。

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

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_时,显然列表中的所有元素都被删除了,因为它们只是映射到变量dict_的地址。

What, I want is to copy the instance of dict_ so that I can store it in the list_. 我想要的是复制dict_的实例,以便我可以将它存储在list_中。

Can someone explain me a way to store the obtained dict in every loop into the list_? 有人可以解释一下将每个循环中获得的dict存储到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_

or better still, have get_values_into_dict() return a dictionary instead: 或者更好的是,让get_values_into_dict() 返回一个字典:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM