【问题标题】:Building Tree Structure from a list of string paths从字符串路径列表构建树结构
【发布时间】:2021-04-07 21:23:05
【问题描述】:

我有一个路径列表

paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6", ...]

列表的实际长度大约为 20,000。我想构建一个可以打印的树结构。树形结构看起来像这样:

x1
├── x2
│   └── x3
├── x4
└── x5
    └── x6

我还希望有一些与节点对象中的每个节点相关联的数据,这些数据当前可以通过字典访问,其中每个节点都是一个键,例如

d = {"x1": [[1,2], [3,4]], "x2": [[5,6], [7,8]], ...}

每个树节点都应该从其父节点继承数据。这样“x2”节点处的数据将为[[1,2], [3,4], [5,6], [7,8]]。

我已经尝试过模块anytree,但它要求您将树的每个节点定义为一个变量。有任何想法吗?提前致谢!

【问题讨论】:

  • 好吧,如果您展示打印时“树”的显示方式会有所帮助。
  • 现在编辑了显示树结构的帖子。
  • 我改变了我的解决方案。如果您指定一个根,它可能会为您节省很多 if-else。我假设x1 是根。

标签: python tree


【解决方案1】:

如果我正确理解您的问题,一种可能的解决方案可能是这样的。

树节点存储它们的父节点以构建混乱的├─── 和└─── 在目录/文件名之前。

输出:

x1
├── x2
│   └── x3
├── x4
└── x5
    └── x6

代码:

class TreeNode:
    def __init__(self, name, parent):
        self.parent = parent
        self.name = name
        self.children = []

    def add_child(self, node):
        self.children.append(node)
        return node

    def print(self, is_root):
        pre_0 = "    "
        pre_1 = "│   "
        pre_2 = "├── "
        pre_3 = "└── "

        tree = self
        prefix = pre_2 if tree.parent and id(tree) != id(tree.parent.children[-1]) else pre_3

        while tree.parent and tree.parent.parent:
            if tree.parent.parent and id(tree.parent) != id(tree.parent.parent.children[-1]):
                prefix = pre_1 + prefix
            else:
                prefix = pre_0 + prefix

            tree = tree.parent

        if is_root:
            print(self.name)
        else:
            print(prefix + self.name)

        for child in self.children:
            child.print(False)

def find_and_insert(parent, edges):
    # Terminate if there is no edge
    if not edges:
        return
    
    # Find a child with the name edges[0] in the current node
    match = [tree for tree in parent.children if tree.name == edges[0]]
    
    # If there is already a node with the name edges[0] in the children, set "pointer" tree to this node. If there is no such node, add a node in the current tree node then set "pointer" tree to it
    tree = match[0] if match else parent.add_child(TreeNode(edges[0], parent))
    
    # Recursively process the following edges[1:]
    find_and_insert(tree, edges[1:])

paths = ["x1/x2", "x1/x2/x3", "x1/x4", "x1/x5/x6"]

root = TreeNode("x1", None)

for path in paths:
    find_and_insert(root, path.split("/")[1:])

root.print(True)

【讨论】:

  • 感谢您的回答!您能否对 find_and_insert() 函数做一些解释?我正在尝试在每个节点中实现一些数据,这些数据从您的类继承自父节点(参见最后一次编辑)..
  • @CosmicPeanutButter 我添加了一些 cmets。基本上find_and_insert(parent, list_of_names) 从树节点parent 中追踪list_of_names,并在必要时在适当的位置插入一个新节点。
  • @CosmicPeanutButter 我忘了提。由于树存储了它的父节点,因此您可以向上遍历以获取每个节点中的关联数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多