可能重复:
python中列表的奇怪行为
我正在尝试初始化一个 6 x 6 的无 2D 数组。这是我所做的:
arr = [[None]*6]*6
然后我尝试插入一些值,如下所示:
arr[2][0] = arr[2][1] = 0
它不是将 (2,0) 和 (2,1) 的值更改为 0 并保持数组的其余部分为无,而是将所有列 0 和 1 更改为 0。
完整示例:
>>> arr = [[None]*6]*6
>>> arr
[[None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None]]
>>> arr[2][0] = arr[2][1] = 0
>>> arr
[[0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None], [0, 0, None, None, None, None]]
为什么会发生这种情况,我该如何预防?
ps我使用“奇怪的行为”这个词对我来说很奇怪,而不是python搞砸了:)