2015-10-31 54 views
1

在以下代碼片段的expand()方法中,類變量的狀態爲未直接指定任何內容。但是,當我調用該方法時,狀態類變量會被修改。爲什麼會發生這種情況,我該如何避免它?我想創建狀態列表的副本,將1或2放在有'*'的位置,並且返回副本而不更改狀態變量的狀態。在python中創建實例變量的副本

例如,如果

self.state = [['*','*','*'],['*','*','*'],['*','*','*']]

孩子的狀態應該是 -

[[1,'*','*'],['*','*','*'],['*','*','*']] 
[['*',1,'*'],['*','*','*'],['*','*','*']] 
[['*','*',1],['*','*','*'],['*','*','*']] 
[['*','*','*'],[1,'*','*'],['*','*','*']] 
[['*','*','*'],['*',1,'*'],['*','*','*']] 
[['*','*','*'],['*','*',1],['*','*','*']] 
[['*','*','*'],['*','*','*'],[1,'*','*']] 
[['*','*','*'],['*','*','*'],['*',1,'*']] 
[['*','*','*'],['*','*','*'],['*','*',1]] 

但我得到下面的輸出 -

[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 
[[1,1,1],[1,1,1],[1,1,1]] 

class Node: 
    def __init__(self, state, node_type, parent=None): 
     self.state=state 
     self.node_type=node_type 
     self.parent=parent 
     self.depth=0 

     if parent: 
      self.depth = parent.depth + 1 

    def __repr__(self): 
     return "<Node %s>" % (self.state,) 

    def expand(self): 
     child_nodes = [] 

     for i in range(0, len(self.state)): 
      for j in range(0, len(self.state[0])): 
       if self.state[i][j] == '*': 
        if self.node_type == 'max': 
         child_state = list(self.state) 
         child_state[i][j] = '1' 
         child_node = Node(child_state,'min',self) 
        elif self.node_type == 'min': 
         child_state = list(self.state) 
         child_state[i][j] = '2' 
         child_node = Node(child_state,'max',self) 
         child_nodes.append(child_node) 

        child_nodes.append(child_node) 

     #print self.state 
     return child_nodes 
+0

你怎麼* *創建的'state'列表,你傳遞給實例? –

+0

@MartijnPieters'start_node = Node([['*','*','*'],['*','*','*'],['*','*','*'] ],'max')output = start_node.expand()' – banad

+1

@PeterWood:不,我現在看到錯誤,這不是一個騙局。 –

回答

4

child_state = list(self.state)創建一個副本的列表。這意味着包含的任何列表本身不會被複制,新的child_state列表僅包含引用。

您可以使用copy.deepcopy() function有Python的遞歸克隆嵌套結構,或者使用列表理解複製直接包含的列表:

child_state = [list(sub) for sub in self.state]