以下示例是人为设计的,仅作为最小的repex。
两件事情按预期工作:
l = list()
for i in range(1, 4):
d = dict() # dict recreated on every iteration
d['index'] = i
l.append(d)
print(l)
print([{'index': i} for i in range(1, 4)])
它们都打印:
[{'index': 1}, {'index': 2}, {'index': 3}]
无法正常工作的事物:
d = dict() # dict created once only
l = list()
for i in range(1, 4):
d['index'] = i
l.append(d)
print(l)
产品:
[{'index': 3}, {'index': 3}, {'index': 3}]
我曾期望index
引用的现有字典的值将在每次传递时都被简单覆盖,然后添加到列表中,并且我会获得一些性能改进(实际上,字典要大得多) 。
几乎看起来好像l.append
只是添加引用而不是传递值。
我错过了令人尴尬的显而易见的东西吗?
我真的很沮丧地发现,除非在每次迭代中都重新创建字典,否则从循环中创建字典列表不会产生预期的结果。以下示例是...
l.append
只是添加了引用而不是传递值。”:就是这样;你什么都没错过。