2016-11-20 78 views
0

我无法围绕为什么我的Python代码以某种方式行事。Python每次迭代打印不同的值,但值不会更改。

既然我不改变“当前”的输出应该是每次迭代相同?这是一个问题,因为我需要“当前”是相同的,所以每个节点都是从相同的起始值生成的。

请看下面的代码:

tester.py

class Node: 
    def __init__(self, board=None): 
     self.board = board 

    def getBoard(self): 
     return self.board 

    def swap(self, xPos, yPos): # swap with zero 

     for a in self.board: 
      if 0 in a: 
       self.board[self.board.index(a)][a.index(0)] = self.board[xPos][yPos] 

     self.board[xPos][yPos] = 0 

open = [] 

def gen_nodes(current): 

    for i in [7, 15, 11]: 

     print(current) # <-- why does this print a different value each time? 

     new = Node(current) 

     for a in new.getBoard(): 
      if i in a: 
       xPos = new.getBoard().index(a) 
       yPos = a.index(i) 

     new.swap(xPos, yPos) 

     open.append(new) 

if __name__ == '__main__': 
    gen_nodes([[1, 2, 3, 4], 
       [8, 5, 6, 7], 
       [9, 10, 11, 0], 
       [12, 13, 14, 15]]) 

输出:

[[1, 2, 3, 4], [8, 5, 6, 7], [9, 10, 11, 0], [12, 13, 14, 15]] 
[[1, 2, 3, 4], [8, 5, 6, 0], [9, 10, 11, 7], [12, 13, 14, 15]] 
[[1, 2, 3, 4], [8, 5, 6, 15], [9, 10, 11, 7], [12, 13, 14, 0]] 
+0

根据我刚刚提出的快速调试会话,问题出现在'new.swap(xPos,yPos)'中。我的意思是,这是'current'变化的地方。仍然试图找出究竟发生了什么.. – noamgot

+1

'def getBoard(self):'这不是Java。不要让吸气者和安装者。 –

回答

2

问题是,您在current保存在节点的board变量内部到数组的引用。这样,当您拨打swap时,此数组已更改。相反,您可能需要在每个节点中新建一个阵列副本,您可以使用copy.deepcopy(node)

0

分配指向一个列表到另一个变量的变量并不意味着副本的清单。

new = Node(current)创建Nodeself.board指向相同的列表,current类型的对象,所以每当你修改newcurrent也被修改。

为了避免这种情况,使用下列:

from copy import copy 

new = Node(copy(current)) 
+1

我打算说同样的;) –