为了加深我在 Python 方面的知识,我已经开始创建一个非常简单的井字游戏 AI。
目前,我对 python 没有预料到的一些行为感到困惑,当我将类实例变量附加到本地列表并更改本地列表中的项目时,实例变量也会发生变化。
如何在不影响类实例变量的情况下仅更改本地列表元素?
这是受影响程序的摘录:
class ticAI:
def __init__(self, board):
self.board = board
self.tic = tictactoe(board)
def calc(self):
possibilities = []
ycord = 0
for y in self.board:
xcord = 0
for x in y:
if x == 0:
possibilities.append(self.board)
possibilities[len(possibilities)-1][ycord][xcord] = 2
print(self.board)
xcord += 1
ycord += 1
self.board 看起来像这样:
[
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]
并输出:
[[2, 0, 0], [0, 1, 0], [0, 0, 0]]
[[2, 2, 0], [0, 1, 0], [0, 0, 0]]
[[2, 2, 2], [0, 1, 0], [0, 0, 0]]
[[2, 2, 2], [2, 1, 0], [0, 0, 0]]
[[2, 2, 2], [2, 1, 2], [0, 0, 0]]
[[2, 2, 2], [2, 1, 2], [2, 0, 0]]
[[2, 2, 2], [2, 1, 2], [2, 2, 0]]
[[2, 2, 2], [2, 1, 2], [2, 2, 2]]
然而,它应该输出:
[[2, 0, 0], [0, 1, 0], [0, 0, 0]]
[[0, 2, 0], [0, 1, 0], [0, 0, 0]]
[[0, 0, 2], [0, 1, 0], [0, 0, 0]]
[[0, 0, 0], [2, 1, 0], [0, 0, 0]]
[[0, 0, 0], [0, 1, 2], [0, 0, 0]]
[[0, 0, 0], [0, 1, 0], [2, 0, 0]]
[[0, 0, 0], [0, 1, 0], [0, 2, 0]]
[[0, 0, 0], [0, 1, 0], [0, 0, 2]]
请您参考如下方法:
正如@jonrsharpe 所说,您可以使用 deepcopy创建变量的副本。
原代码:
possibilities.append(self.board)
possibilities[len(possibilities)-1][ycord][xcord] = 2
print(self.board)
新代码:
b = copy.deepcopy(self.board)
possibilities.append(b)
possibilities[len(possibilities)-1][ycord][xcord] = 2
print(self.board)
