我在玩list
时发现了一些奇怪的东西。我通常使用print()
来调试或了解事情是如何工作的,但在这种情况下,print()
输出根本没有帮助我。
这是一个简单的代码,您将很快看到我在谈论的内容:
a = [[]] * 5
b = [[]] * 5
b[0] = []
b[1] = []
b[2] = []
b[3] = []
b[4] = []
# It prints the same thing:
print(a) # [[], [], [], [], []]
print(b) # [[], [], [], [], []]
a[0] += ["test"]
b[0] += ["test"]
# Different results:
print(a) # [['test'], ['test'], ['test'], ['test'], ['test']]
print(b) # [['test'], [], [], [], []]
我希望a
的行为与b
相似,但事实并非如此。有人可以解释一下吗?