为什么? - 除非在每次迭代时重新创建字典,否则从循环构建字典列表不起作用

Why? - Constructing a list of dictionaries from a loop doesn't work unless the dictionary is recreated on every iteration

我真的很难过发现从循环创建字典列表不会产生预期的结果,除非在每次迭代时重新创建字典。

以下示例是人为设计的,仅用作最小的重复。

有两件事按预期工作:

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 只是添加了引用而不是传递值。

我是不是漏掉了一些非常明显的东西?

"It almost appears as if l.append just added references instead of passing values.":就是这样;你没有错过任何东西。

正如其他人所说,Python 将通过 reference.But 你可以这样做:

for i in range(1, 4):
    d['index'] = i
    l.append(d.copy())

为了得到你想要的结果。