简体   繁体   English

Python追加循环工作之谜

[英]Python append in loop working mystery

I found some "mystery" problem when I'm trying filling list in "for in" loop. 我尝试在“ for in”循环中填充列表时发现一些“神秘”问题。

Here is example: 这是示例:

>>> params = [1,2,3,4,5]
>>> el = {'param':0}
>>> el
{'param': 0}
>>> list = []
>>> for param in params:
...     el['param'] = param
...     list.append(el)
... 
>>> print(list)
[{'param': 5}, {'param': 5}, {'param': 5}, {'param': 5}, {'param': 5}]
>>> 

But I think result should be 但我认为结果应该是

>>> print(list)
[{'param': 1}, {'param': 2}, {'param': 3}, {'param': 4}, {'param': 5}]
>>> 

How to resolve this problem? 如何解决这个问题? And why real result isn't similar with result in my mind? 为什么真正的结果与我脑海中的结果不一样?

Every element in your list contains a reference to the same dict. 列表中的每个元素都包含对同一字典的引用。 That is why you are seeing the same number in every element. 这就是为什么您在每个元素中看到相同数字的原因。 Perhaps you want to do: 也许您想做:

params = [1,2,3,4,5]

a = []
for param in params:
    el = {'param': param}
    a.append(el)

Also, be careful of shadowing builtins such as list with your variable names. 另外,请注意不要将内置变量(例如带有变量名的list遮盖起来。

el refers to the same dictionary throughout, and list.append(el) adds a reference to that dictionary, not a copy of its current value, to the list. el始终引用同一词典, list.append(el)添加对该词典的引用 ,而不是其当前值的副本。 You don't have a list of 5 different dictionaries, but a list of 5 references to one dictionary. 您没有5个不同字典的列表,但是有5个引用到一个字典的引用的列表。

To see what is happening in closer detail, print list and el each time through the loop. 要更详细地了解正在发生的事情,请在循环中每次打印listel You'll see a growing list that always refers to the current value of el . 您会看到一个不断增长的列表,该列表始终引用el的当前值。

The problem is that you are using the same dictionary for each entry in your list. 问题是您为列表中的每个条目使用相同的字典。 To fix this problem, add el = {} above el['param'] = param in your for loop. 要解决此问题,请在for循环中的el['param'] = param上方添加el = {}

You modify the same dict in every iteration and add it to the list . 您可以在每次迭代中修改相同的dict并将其添加到list You'll get the other result when adding copies of this dict to the list . 将此字典的副本添加到list时,会得到其他结果。

Just call list.append(dict(el)) instead. 只需调用list.append(dict(el))

You have one dict object that you are modifying. 您有一个要修改的字典对象。 You add a reference to that one dict to your list multiple times. 您多次将对该字典的引用添加到列表中。 So your list contains 5 references to the same dict object. 因此,您的列表包含对同一dict对象的5个引用。

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

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