【发布时间】:2012-11-19 07:14:49
【问题描述】:
已解决:问题似乎只出现在 PythonWin 中。我通过 IDLE 的 python shell 运行了所有东西,它工作得很好。必须是 PythonWin 的错误,而不是代码本身。
我似乎无法弄清楚为什么下面的代码给了我一个TypeError: 'type' object is not iterable
粘贴箱:http://pastebin.com/VFZYY4v0
def genList(self):
#recursively generates a sorted list of child node values
numList = []
if self.leftChild != 'none':
numList.extend(self.leftChild.genList()) #error
numList.extend(list((self.Value,)))
if self.rightChild != 'none':
numList.extend(self.rightChild.genList()) #error
return numList
添加子节点的代码(正常工作)
def addChild(self, child):
#add a child node. working
if child.Value < self.Value:
if self.leftChild == 'none':
self.leftChild = child
child.parent = self
else:
self.leftChild.addChild(child)
elif child.Value > self.Value:
if self.rightChild == 'none':
self.rightChild = child
child.parent = self
else:
self.rightChild.addChild(child)
任何帮助将不胜感激。
完整的口译会话:
>>> 将 BinTreeNode 导入为 BTN
>>> node1 = BTN.BinaryTreeNode(5)
>>> node2 = BTN.BinaryTreeNode(2)
>>> node3 = BTN.BinaryTreeNode(12)
>>> node3 = BTN.BinaryTreeNode(16)
>>> node4 = BTN.BinaryTreeNode(4)
>>> node5 = BTN.BinaryTreeNode(13)
>>> node1.addChild(node2)
>>> node1.addChild(node3)
>>> node1.addChild(node4)
>>> node1.addChild(node5)
>>> node4.genList()
>>> node1.genList()
回溯(最近一次通话最后一次):
中的文件“”,第 1 行
文件“C:...\python\BinTreeNode.py”,第 47 行,在 genList
numList.extend(self.leftChild.genList()) #error
文件“C:...\python\BinTreeNode.py”,第 52 行,在 genList
TypeError:“类型”对象不可迭代
【问题讨论】:
-
你能发布整个错误吗?或更多代码。 leftChild 和 rightChild 是如何生成的?
-
@JacobJCallahan 不要在 cmets 中发布信息,因为您无法正确格式化它。编辑您的问题。
-
从您提供的代码来看,
numList.extend()似乎总是会收到一个列表实例。我觉得这只能通过查看所有代码来解决:-/ -
numList.extend(list((self.Value,)))似乎应该只是numList.append(self.Value)...(这不是你的问题,但它会不那么令人困惑)——你没有碰巧隐藏了内置的list是吗? -
@jgritty:不,那是错误的。这将附加一个嵌套列表,这不是 OP 想要的。
标签: python recursion binary-tree