我对 Python 还是有点陌生,但是,我现在觉得很愚蠢,因为我刚刚花了一个小时试图弄清楚为什么这个 for 循环没有做我想要的。我不应该在 for 循环上花费一个小时。无论如何,我正在尝试生成一个字典列表,并给它们每个一个唯一的数字,所以我这样做......
def initiate(n):
records = {'num':0,'blah':0,'doubleblah':0}
x = []
for i in range(n):
x.append(records)
x[i]['num'] = i
return x
x = initiate(4)
print(x)
我希望函数返回这个——
[
{'num': 0, 'doubleblah': 0, 'blah': 0},
{'num': 1, 'doubleblah': 0, 'blah': 0},
{'num': 2, 'doubleblah': 0, 'blah': 0},
{'num': 3, 'doubleblah': 0, 'blah': 0}
]
但它实际上返回了这个——
[
{'num': 3, 'doubleblah': 0, 'blah': 0},
{'num': 3, 'doubleblah': 0, 'blah': 0},
{'num': 3, 'doubleblah': 0, 'blah': 0},
{'num': 3, 'doubleblah': 0, 'blah': 0}
]
...当我在函数中添加一些打印语句时,我发现它似乎将数字添加到列表中的每个字典,而不仅仅是当前字典。我真的不知道代码将如何添加到所有字典中,因为我明确使用x[i] = i
仅将数字添加到当前字典中。