从列表中引用的Python类变量

为了进一步了解python,我开始创建一个非常简单的tic tac toe 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]]

回答(1)

3 years ago

正如@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)