我正在尝试创建一个 connect 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 时,提供的列中的每个插槽都会更新。为什么会发生这种情况?
最佳答案
问题出在这里:
self.board = [[0] * width] * height
执行此操作时,self.board
包含对 [0]*width
同一行的 height
引用。现在您需要将其更改为
self.board = [[0]*width for _ in range(height)]
关于Python - 对单个元素的更新会影响同一列中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54057308/