使用 Treelib 遍历树数据结构 (Python)

Iterating through tree datastructure using Treelib (Python)

我通过 Node-class 创建了一些节点,并使用 Treelib 将它们添加到树中。

class Node(object):
    def __init__(self, id, label, parent, type):
        self.id = id
        self.label = label
        self.parent = parent
        self.type = type

node = Node(id, label, parent, type)

if id == 'root':
   tree.create_node(tag=id, identifier=id, data=node)
else:
   tree.create_node(tag=id, identifier=id, parent=parent, data=node)

通过调用 tree.show(),我对这棵树有了一个很好的了解。 现在我想遍历树并获取前面定义的每个节点的数据。 (不仅是单个 属性 by tree.show(data_property=""))

您对如何使用定义的数据有任何想法吗?

我的最终目标是像决策树一样计算树结构,到目前为止我没有找到使用 Treelib 的好方法。

先说几点:

  • 我会为 class Node 使用不同的名称; TreeLib 还定义了一个 Node class.
  • 当您使用 TreeLib 时,不需要在您自己的 class 实例中维护父引用。这是 TreeLib 已经为您管理的东西。

您可以使用 all_nodes_itr 方法遍历节点,这将在每次迭代中为您提供一个 TreeLib Node 实例。然后,您可以访问 identifierparent 等 TreeLib 属性。对于您自己的属性,访问 data 属性,然后是您要查看的属性(如 label

这是一个简化的脚本:

class MyNode(object):
    def __init__(self, id, label):
        self.id = id
        self.label = label


from treelib import Tree
tree = Tree()

def add_node(id, label, parent=None):
    node = MyNode(id, label)
    tree.create_node(tag=id, identifier=id, data=node, parent=parent)

add_node("world", "World")
add_node("north-america", "North America", "world")
add_node("europe", "Europe", "world")

for node in  tree.all_nodes_itr():
    print(node.identifier, node.data.label)