【问题标题】:List of branches of a Python treePython 树的分支列表
【发布时间】:2017-12-19 07:26:03
【问题描述】:

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

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

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

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

我正在尝试递归方法:

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

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

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

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

谢谢

【问题讨论】:

  • 考虑使用中序遍历。左-右-右

标签: python tree


【解决方案1】:

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

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)
    ]

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

【讨论】:

  • 像魅力一样工作,谢谢:D 我明白了:[[Node_0001, Node_0002, Node_0004], [Node_0001, Node_0002, Node_0005, Node_0007], [Node_0001, Node_0003, Node_0006]]
猜你喜欢
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
相关资源
最近更新 更多