我想要这样的输出:
[{'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 newdictionary
Infor-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}]