简体   繁体   English

从后代列表构建一棵 python 富有的树

[英]construct a python rich tree from list of descendants

I am trying to construct a python rich.Tree from a list of descendants, d .我正在尝试从后代列表d构建一个 python rich.Tree

d = {0: [1, 2], 2: [3, 4, 5], 4: [6, 7]}

I expect to get something like this:我希望得到这样的东西:

# manually constructed string
expected = \
"""
0
├── 1
└── 2
    └── 3
    └── 4
        └── 6
        └── 7
    └── 5
"""

But I am getting confused as to how to proceed with the construction: the following code is not correct.但是我对如何进行构建感到困惑:以下代码不正确。

from rich.tree import Tree
from rich import print as rprint

tree = Tree("0")
tree.add("1")
tree.add("2").add("3")
tree.add("4").add("6").add("7")
tree.add("5")
rprint(tree)

0
├── 1
├── 2
│   └── 3
├── 4
│   └── 6
│       └── 7
└── 5

Any suggestions will be appreciated, thanks!任何建议将不胜感激,谢谢!

The following should work:以下应该工作:

from rich.tree import Tree
from rich import print as rprint

tree = Tree("0")
tree.add("1")
tree.add("2").add("3")
four_branch = tree.add("4")
four_branch.add("6")
four_branch.add("7")
tree.add("5")
rprint(tree)

If you look at the example they linked to in the documentation, you'll see that the tree.add(...) returns a value that you can then add to如果您查看他们在文档中链接到的示例,您会看到tree.add(...)返回一个值,然后您可以将其添加到

You could use a recursive function to convert the dictionary representation of your tree (ie the adjacency list) to the nested tree object:您可以使用递归 function 将树的字典表示(即邻接列表)转换为嵌套树 object:

def make_tree(adj, node=0):
    tree = Tree(str(node))
    for child in adj.get(node, []):
        tree.add(make_tree(adj, child))
    return tree

Call like this:像这样调用:

d = {0: [1, 2], 2: [3, 4, 5], 4: [6, 7]}
tree = make_tree(d)
rprint(tree)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM