在以下代码段的expand()方法中,类变量 state 没有直接分配任何内容。但是,当我调用该方法时,状态类变量会被更改。为什么会发生这种情况,我该如何避免呢?我想创建状态列表的副本,放置1或2,其中有一个' *'并返回副本而不更改状态变量 state。
例如,如果
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 :(得分:4)
child_state = list(self.state)
创建列表的浅副本。这意味着任何列出包含的列表本身都不会被复制,新的child_state
列表只包含引用。
您可以使用copy.deepcopy()
function以递归方式克隆嵌套结构,或使用列表推导来复制直接包含的列表:
child_state = [list(sub) for sub in self.state]