2016-05-14 53 views
2

爲了進一步提高我在python方面的知識,我開始創建一個非常簡單的tic tac toe AI。從列表中引用的Python類變量

目前,我很難從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]] 
+2

你應該看看'deepcopy' ... – jonrsharpe

+0

@jonrsharpe非常感謝你! deepcopy已經解決了這個問題。你應該發佈一個問題的答案 – robinp7720

+1

爲了說明,'possible.append(copy.deepcopy(self.board))' –

回答

1

由@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)