所以我不知道是什么导致了这个错误。我不知道如何在不向您展示的情况下对其进行描述,所以这是我的代码的相关部分:
class Node(object):
def __init__(self, contents, children):
self.contents = contents
self.children = children
def makeNode(district, parent):
new_contents = parent.contents
new_contents.append(district)
new = Node(new_contents, [])
parent.children.append(new)
return new
root = Node([], [])
data = [[1,1,'r'],[1,2,'d'],[1,2,'r'],[1,4,'d']]
makeNode(data, root)
问题在于:new.contents按计划更改,但parent.contents也是如此。发生了什么事?
答案 0 :(得分:0)
正如您在评论中提到的那样,您必须将内容 pf'parent.contents'复制到'new_contents'中。否则,您将通过引用访问列表,这显然不是预期的。
所以,你的'makeNode'函数可以如下开始:
def makeNode(district, parent):
new_content = copy.deepcopy(parent.contents)
...
我希望,我可以为后来的读者清理......;)