Python 树的分支列表 [英] List of branches of a Python tree

查看:27
本文介绍了Python 树的分支列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵 Python 对象树.树是内在定义的:每个对象都有一个子项列表(可能为空).我希望能够打印从根到每个叶子的所有路径的列表.

I have a tree of Python objects. The tree is defined intrinsically: each object has a list (potentially empty) of children. I would like to be able to print a list of all paths from the root to each leaf.

在上面的树的情况下,这意味着:

In the case of the tree above, this would mean:

result = [
          [Node_0001,Node_0002,Node_0004],
          [Node_0001,Node_0002,Node_0005,Node_0007],
          [Node_0001,Node_0003,Node_0006],
         ]

必须将节点视为对象而不是整数(仅显示其整数 ID).我不关心结果中分支的顺序.每个节点有任意数量的子节点,递归级别也不固定.

The nodes must be treated as objects and not as integers (only their integer ID is displayed). I don't care about the order of branches in the result. Each node has an arbitrary number of children, and the level of recursion is not fixed either.

我正在尝试递归方法:

def get_all_paths(node):
    if len(node.children)==0:
        return [[node]]
    else:
        return [[node] + get_all_paths(child) for child in node.children]

但我最终得到了嵌套列表,这不是我想要的:

but I end-up with nested lists, which is not what I want:

[[Node_0001,
  [Node_0002, [Node_0004]],
  [Node_0002, [Node_0005, [Node_0007]]]],
 [Node_0001, [Node_0003, [Node_0006]]]]

欢迎任何帮助,这个问题让我发疯:p

谢谢

推荐答案

我认为这就是您正在尝试的:

I think this is what you are trying:

def get_all_paths(node):
    if len(node.children) == 0:
        return [[node]]
    return [
        [node] + path for child in node.children for path in get_all_paths(child)
    ]

对于节点的每个子节点,您应该获取子节点的所有路径并将节点本身添加到每个路径.您将节点添加到路径列表中,而不是单独添加每个路径.

For each child of a node, you should take all paths of the child and prepend the node itself to each path. You prepended the node to the list of paths, not every path individually.

这篇关于Python 树的分支列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆