【问题标题】:Modifying list result in changing another list that is only being copied at the beginning修改列表会导致更改仅在开头复制的另一个列表
【发布时间】:2019-09-18 05:57:16
【问题描述】:
def move(board, dir):
    tempt = []
    tempt = board[:]
    #print(tempt)
    if dir == 'down':
        for a in range(Grids):
            for b in range(Grids-1, -1, -1):
                if board[a][b] != 0:
                    check = CheckBlock(a, b, dir)
                    board[a][b].moving(board, dir, check[1], check[0])
                    #print(tempt)                   
    if dir == 'up':
        for a in range(Grids):
            for b in range(Grids):
                if board[a][b] != 0:
                    check = CheckBlock(a, b, dir)
                    board[a][b].moving(board, dir, check[1], check[0])
    if dir == 'left':
        for a in range(Grids):
            for b in range(Grids):
                if board[b][a] != 0:
                    check = CheckBlock(b, a, dir)
                    board[b][a].moving(board, dir, check[1], check[0])
    if dir == 'right':
        for a in range(Grids):
            for b in range(Grids-1, -1, -1):
                if board[b][a] != 0:
                    check = CheckBlock(b, a, dir)
                    board[b][a].moving(board, dir, check[1], check[0])

当我偶然发现这个烂摊子时,我正在重新创建一些游戏。因此,这是一个在更改列表本身(即板)的同时移动列表中所有内容的功能。最后,我想确保列表中的某些内容发生了变化。所以我做了一个临时列表(很诱人)并复制了基本列表以供以后比较。但是当基础列表被修改时,临时列表也会被修改。所以这两个#print(tempt) 代码会打印出不同的列表。

我已尽力指出问题,只调用了一次函数,但不知何故,每当我对基本列表进行任何修改时,临时列表都会不断变化。

非常感谢您阅读此处,感谢您提供任何帮助或想法。

【问题讨论】:

  • 你知道什么是浅拷贝吗?如果没有,请查看this QA

标签: python python-3.x list function


【解决方案1】:

为了模拟问题,您现在正在做的事情如下:

>>> a=[[1,2,3,4]]
>>> a
[[1, 2, 3, 4]]
>>> b=a[:]
>>> b
[[1, 2, 3, 4]]
>>> a[0].append(5);
>>> a
[[1, 2, 3, 4, 5]]
>>> b
[[1, 2, 3, 4, 5]]
>>> a.append(6)
>>> a
[[1, 2, 3, 4, 5], 6]
>>> b
[[1, 2, 3, 4, 5]]

您认为只需执行 b=a[:] 即可删除所有引用,但现在它的工作方式仍然是浅拷贝。为避免这种行为,您必须使用 深拷贝,如下所示:

>>> import copy
>>> a=[[1,2,3]]
>>> b=copy.deepcopy(a);
>>> a
[[1, 2, 3]]
>>> b
[[1, 2, 3]]
>>> a[0].append(4);
>>> a
[[1, 2, 3, 4]]
>>> b
[[1, 2, 3]]

所以在你的代码中替换 tempt = board[:]tempt = copy.deepcopy(board)

【讨论】:

  • 非常感谢,我刚开始编码,所以对我来说一切都是新的。
  • 别担心,你可以通过练习变得更好。祝你好运:)
猜你喜欢
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
相关资源
最近更新 更多