更改列表中列表的第n个元素会更改列表中所有列表的第n个元素

时间:2017-12-13 20:25:03

标签: python list

我有一个tictactoe程序,它首先创建一个游戏计划,其中每一行都是一个包含空填充符号的列表,这意味着该正方形为空。

def createGamePlan(size, sign): 
    gPlan = []
    row = [sign]*size
    for i in range(size):
      gPlan.append(row)
    return gPlan

用户选择行和列时,我希望更新该特定元素的符号。因此,如果我想将第2行的第1列更新为" X"我会

def updateGamePlan(row, col, gamePlan, sign):
    gamePlan[1][0] = "X"

然而,这改变了每一行的第一列,我无法弄清楚原因。我指定它的第2行(gamePlan列表的第1个元素,以及该内部列表的第0个元素,即第1列)。有人可以指出出了什么问题,我在上面的例子中只能让它改变第二行的第一列,而不是每一行

1 个答案:

答案 0 :(得分:3)

要理解的关键是list个对象没有行和列。列表对象是有序的,异构的对象序列。当你这样做时:

def createGamePlan(size, sign): 
    gPlan = []
    row = [sign]*size
    for i in range(size):
      gPlan.append(row) # appends the SAME object
    return gPlan

所以,请考虑以下事项:

>>> a = ['foo']
>>> bar = []
>>> for _ in range(4):
...     bar.append(a)
...
>>> [id(x) for x in bar]
[4534044744, 4534044744, 4534044744, 4534044744]

对象都是一样的!

>>> bar[0].append('baz')
>>> bar
[['foo', 'baz'], ['foo', 'baz'], ['foo', 'baz'], ['foo', 'baz']]

您创建的列表多次包含同一个对象。一个办法?附加副本

def createGamePlan(size, sign): 
    gPlan = []
    row = [sign]*size
    for i in range(size):
      gPlan.append(row.copy()) # appends a NEW object
    return gPlan

但要小心,因为.copy只生成副本。考虑:

>>> row = [['foo'], ['bar']]
>>> grid = []
>>> for _ in range(5):
...     grid.append(row.copy())
...
>>> grid
[[['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']]]

好的,膨胀!这些都是独立的对象!:

>>> [id(x) for x in grid]
[4534044616, 4534135432, 4534135560, 4534135176, 4534135688]

所以...这应该可以正常工作,不是吗?

>>> grid[0][0].append('baz')
>>> grid
[[['foo', 'baz'], ['bar']], [['foo', 'baz'], ['bar']], [['foo', 'baz'], ['bar']], [['foo', 'baz'], ['bar']], [['foo', 'baz'], ['bar']]]

发生了什么?好吧,浅拷贝创建了新列表,但没有创建新的子列表,即它没有复制元素中包含的任何元素:

>>> [id(x) for row in grid for x in row]
[4534135048, 4534135112, 4534135048, 4534135112, 4534135048, 4534135112, 4534135048, 4534135112, 4534135048, 4534135112]
>>>

为此,您需要 deepcopy

>>> import copy
>>> row = [['foo'], ['bar']]
>>> grid = []
>>> for _ in range(5):
...     grid.append(copy.deepcopy(row))
...
>>> grid
[[['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']]]
>>> [id(x) for row in grid for x in row]
[4534135432, 4534135368, 4534135176, 4534135880, 4534136328, 4534161928, 4534135112, 4534162120, 4534162248, 4534162184]
>>> grid[0][0].append('baz')
>>> grid
[[['foo', 'baz'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']], [['foo'], ['bar']]]
>>>