追加字典数组



这让我很困惑。这是我代码的一个非常简化的版本,但显示了确切的问题:

test={"number":"0"}
testarray=[test]
print(testarray)
for x in range(5):
test["number"] = x
print(test)
testarray.append(test)
print("TestArray")
for x in testarray:
print(x)

输出为:

[{'number': '0'}]
{'number': 0}
{'number': 1}
{'number': 2}
{'number': 3}
{'number': 4}
TestArray
{'number': 4}
{'number': 4}
{'number': 4}
{'number': 4}
{'number': 4}
{'number': 4}

为什么所有条目都设置为字典的最后一个值?我也尝试过testarray.insert(len(testarray),test),得到了同样的结果。

我认为您在列表中多次放入同一dict。每次在同一个dict中更改数字,列表就会存储对dict的引用。

testarray = []
for i in range(5):
test = {"number": i}
testarry.append(test)
test={"number":"0"}

这一行创建了一个新的字典对象,其中关键字"number"与值"0"相关联。它还在本地作用域中创建一个名称test,并将该名称与dictionary对象相关联。

稍后在你的代码中,你有这行

test["number"] = x

它将采用名称test引用的对象(在这种情况下是在前一行创建的字典(,更新与该对象内的关键字"number"相关联的值,以引用x引用的同一对象(在该情况下是数字0、1、2、3,然后是4(。

testarray.append(test)

此行将对该字典的引用添加到名称testarray引用的数组的末尾。由于它每次都会添加对同一词典的引用,因此对该词典的任何更改都将反映在所有引用中。

要查看相同错误的简单示例,请尝试以下代码:

foo = {'x': 0}
bar = [foo, foo, foo]
foo['x'] = 1
print(bar)

要修复您的代码,我建议:

testarray = []
for x in range(5):
testarray.append({"number": x})

或者更惯用的

testarray = [ {"number": x} for x in range(5) ]

最新更新