我有这个7x7二维数组:
l=[[1, 1, 1, 1, 1, 1, 1],
[1, 0, 2, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]]
如您所见,l [1] [2] = 2。当我打印它时,元素被正确打印。这里没问题。但是当我尝试将其从“2”更改为“3”或任何其他数字时,程序会更改该列上的所有元素(在本例中为第3列),但第一列和最后一列除外。例如,如果我输入以下代码:
l[1][2]=5
然后打印二维数组,我明白了:
l=[[1, 1, 1, 1, 1, 1, 1],
[1, 0, 5, 0, 0, 0, 1],
[1, 0, 5, 0, 0, 0, 1],
[1, 0, 5, 0, 0, 0, 1],
[1, 0, 5, 0, 0, 0, 1],
[1, 0, 5, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]]
我选择的每个元素都会发生这种情况。它不是仅更改该元素,而是更改整个列。 有谁知道可能是什么问题?谢谢!
答案 0 :(得分:27)
即使您描述的行为(正如您所描述的那样)是不可能的,我也会尝试这一行。
如果您创建列表,则需要确保每个子列表都是不同的列表。考虑:
a = []
b = [a, a]
这里我创建了一个列表,其中两个子列表都是完全相同的列表。如果我改变一个,它将出现在两者中。 e.g:
>>> a = []
>>> b = [a, a]
>>> b[0].append(1)
>>> b
[[1], [1]]
使用*
运算符初始化列表时,您经常会看到此行为:
a = [[None]*7]*7
e.g。
>>> a = [[None]*7]*7
>>> a
[[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, None, None, None, None, None, None], [None, None, None, None, None, None, None]]
>>> a[0][1] = 3
>>> a
[[None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None]]
修复是不使用外部列表上的*
7(内部列表没有问题,因为None
是不可变的):
a = [[None]*7 for _ in range(7)]
e.g:
>>> a = [[None]*7 for _ in range(7)]
>>> a[0][1] = 3
>>> a
[[None, 3, 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, None, None, None, None], [None, None, None, None, None, None, None]]
答案 1 :(得分:2)
你错误地构建了你的列表。
中间项目都指向同一个列表,因此更新一个会导致更改反映在其他项目中
如果您显示用于构建列表的代码,我可以向您展示如何修复它。
可选地
l = [sublist[:] for sublist in l]
在开始修改列表之前,会将所有这些列表拆分为新列表