2016-11-18 52 views
-2
def get_all_children(self): 
    zero = self.current_coords[0] 
    zero_row, zero_col = zero 
    states = [] 
    # blank spot is not on top row(middle or bottom) so we move up! 
    if zero_row > 0: 
     swapRow = zero_row - 1 
     tempState = copy.copy(self.current) # a list of list of strings 
     tempState[zero_row][zero_col], tempState[swapRow][zero_col] = tempState[swapRow][zero_col], tempState[zero_row][zero_col] 
     s = State(tempState) 
     states.append(s) 
    ## blank spot is not on the bottom row(middle or top) so we move down! 
    if zero_row < 2: 
     swapRow = zero_row + 1 
     tempState = copy.copy(self.current) 
     tempState[zero_row][zero_col], tempState[swapRow][zero_col] = tempState[swapRow][zero_col], tempState[zero_row][zero_col] 
     s = State(tempState) 
     states.append(s) 

我有一个State类,其中包含名为'current'的列表,并且我试图定义一个函数来获取所有可能的子元素(移动)当前状态。在第一个IF语句中,我创建当前变量(这是一个列表列表)的COPY并将其存储在'tempState'列表中,然后我尝试在该tempState上交换值,创建一个State对象,并将其传入并然后将该对象附加到列表中。所有的工作正常。问题在于何时到达第二个IF语句。在我做了交换之后,它修改了原来的'当前'变量,即使我创建了一个副本!我无法弄清楚为什么。 我试过list(self.current),self.current [:],copy.cop(self.current)。请帮助Python原始列表被复制后仍被修改

+0

您是否阅读过[文档](https://docs.python.org/2/library/copy.html)? – BrenBarn

+0

请发布'State'类的代码,否则我们看不到您的引用错误的位置。 – KeatsKelleher

+0

正如BrenBarn所说的,如果您要复制列表列表,您需要'deepcopy()'。 – TemporalWolf

回答

1

您必须改用copy.deepcopy(x)。

+0

谢谢!我没有想到这样做,因为我认为这是因为如果我想复制具有属性的对象。 – David