Python while循环!=0

2024-09-30 22:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我对while循环有问题:

  def ancestors(node, tree):
        ancestorsss = []
        ancestorsss.append(node.value)
        parent = node.parent
        while(parent != 0):
            parent_node = find_node(parent, tree)
            parent = parent_node.parent
            ancestors(parent_node, tree)
        return ancestorsss

在我的例子中,第一个父级是4,它应该经过while循环,在第二次迭代中,父级是2,也可以,第三次父级是1,也可以,然后父级是0,while循环仍然继续?我认为它应该在parent=0时退出,但它没有。你知道吗

编辑: 节点是具有值和父级的对象。 树是节点对象的列表[(1,0),(2,1),(3,1),(4,2),(5,2),(6,3),(7,3),(8,4),(9,4)]。你知道吗

现在我用节点(8,4)调用祖先函数,并认为它应该是(8,4),(4,2),(2,1)和(1,0)。它不会以(1,0)停止

编辑2:

def find_node(parent, tree):
    node = next((x for x in tree if x.value == parent), None)
    return node

Tags: 对象nodetree编辑return节点valuedef
1条回答
网友
1楼 · 发布于 2024-09-30 22:09:55

很可能是父变量类型中的问题,请确保它是整数或将条件更改为while parent != "0"。你知道吗

如果以上都不是,你可以分享更多关于nodenode.parent的细节

相关问题 更多 >