追加字典到列表中一个循环的Python [英] Appending a dictionary to a list in a a loop Python
问题描述
我是一个基本的Python程序员所以希望回答我的问题会很容易。
我试图把一本字典,并追加到列表中。该字典然后更改值,然后在循环再追加。似乎每一次我这样做的时候,在列表中的所有词典改变它们的值以匹配只是追加一个。
例如:
I am a basic python programmer so hopefully the answer to my question will be easy. I am trying to take a dictionary and append it to a list. The dictionary then changes values and then is appended again in a loop. It seems that every time I do this, all the dictionaries in the list change their values to match the one that was just appended. For example:
>>> dict = {}
>>> list = []
>>> for x in range(0,100):
... dict[1] = x
... list.append(dict)
...
>>> print list
我将承担结果将是 [{1:1},{1:2},{1:3} ... {1:98},{} 1:99]
而是我得到了:
[{1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}]
任何帮助是极大AP preciated。
Any help is greatly appreciated.
推荐答案
您需要追加的复制的,否则你只是添加引用同一个字典一遍又一遍:
You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:
yourlist.append(yourdict.copy())
我用 yourdict
和 yourlist
而不是字典
和列表
;你不想掩盖内置类型。
I used yourdict
and yourlist
instead of dict
and list
; you don't want to mask the built-in types.
这篇关于追加字典到列表中一个循环的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!