【发布时间】: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