将不同的值附加到字典列表中的相同名称键



我想要这样的输出:

[{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]

但是我得到这样的输出:

[{'a': 3}, {'a': 3}, {'a': 3}, {'a': 3}]

我尝试了下面的代码:

l = []
d = {}
for i in range(0,4):
d['a'] = i
print("dictinary ",d)
print("list before appending ",l)
l.append(d)
print("list after appending ",l)
print(l)

在应用print语句(用于调试)后,我得到以下输出

dictinary  {'a': 0}
list before appending  []
list after appending  [{'a': 0}]
dictinary  {'a': 1}
list before appending  [{'a': 1}]
list after appending  [{'a': 1}, {'a': 1}]
dictinary  {'a': 2}
list before appending  [{'a': 2}, {'a': 2}]
list after appending  [{'a': 2}, {'a': 2}, {'a': 2}]
dictinary  {'a': 3}
list before appending  [{'a': 3}, {'a': 3}, {'a': 3}]
list after appending  [{'a': 3}, {'a': 3}, {'a': 3}, {'a': 3}]
[{'a': 3}, {'a': 3}, {'a': 3}, {'a': 3}]

我不能理解一件事:为什么我的列表值在改变字典值时被改变?。在执行代码中的第4行时,列表的值被自动更改(参见输出的第5行)。请提出建议。

create newdictionaryInfor-loop。在你的代码中,当改变其中一个时,你有一个dictionary和一个address。试试这个:

l = []
for i in range(0,4):
d = {}
d['a'] = i
print("dictinary ",d)
print("list before appending ",l)
l.append(d)
print("list after appending ",l)
print(l)

输出:

dictinary  {'a': 0}
list before appending  []
list after appending  [{'a': 0}]
dictinary  {'a': 1}
list before appending  [{'a': 0}]
list after appending  [{'a': 0}, {'a': 1}]
dictinary  {'a': 2}
list before appending  [{'a': 0}, {'a': 1}]
list after appending  [{'a': 0}, {'a': 1}, {'a': 2}]
dictinary  {'a': 3}
list before appending  [{'a': 0}, {'a': 1}, {'a': 2}]
list after appending  [{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]
[{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]

相关内容

  • 没有找到相关文章

最新更新