【问题标题】:Python - Update to single element is affect all elements in same column [duplicate]Python - 更新单个元素会影响同一列中的所有元素[重复]
【发布时间】:2019-06-01 02:37:59
【问题描述】:

我正在尝试创建一个连接 4 类,但每当我删除一个字母/令牌时,它都会更新整个列。我一生都无法弄清楚为什么会发生这种情况:

class ConnectFour():
def __init__(self, width, height):
    self.width = width
    self.height = height        
    self.board = [[0] * width] * height

def dropLetter(self, letter, col):
    count = self.height - 1
    while count > 0 and self.board[count][col] != 0:
        count -= 1
    print self.board[count][col] 
    self.board[count][col] = letter     
    print self.board

C = ConnectFour(4,4)
C.dropLetter('X', 0)

然后,当我打印 self.board 时,提供的列中的每个插槽都在更新。为什么会这样?

【问题讨论】:

  • [[0] * width] * height 是你的问题。

标签: python arrays multidimensional-array


【解决方案1】:

问题来了:

self.board = [[0] * width] * height

当您这样做时,self.board 包含 height 对同一行 [0]*width 的引用。现在你需要把它改成

self.board = [[0]*width for _ in range(height)]

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2018-07-30
    • 2021-09-10
    • 2023-04-01
    • 2021-01-15
    相关资源
    最近更新 更多