我有一个嵌套列表,如下所示:
lst = [['a', 'b', 'e'], # this e is the branch of b
['a', 'f', 'e'], # this e is the branch of f,
['a', 'h', 'i i i']] # string with spaces
我想构建一棵树,例如:
a
├── b
│ └── e
├── f
| └── e
└── h
└── i i i
我想使用两个包中的任何一个:treelib和anytree。我已经阅读了很多帖子并尝试了许多不同的方法,但都没有成功。
更新:
我想出了以下方法,但我现在遇到的问题是
- 不能保证分支的垂直顺序(例如,“b”、“f”、“h”)(当我在 list 中有很多列表时)。
- “e”作为“f”的一个分支不会出现
from treelib import Node, Tree
# make list flat
lst = sum([i for i in lst], [])
tree = Tree()
tree_dict = {}
# create root node
tree_dict[lst[0]] = tree.create_node(lst[0])
for index, item in enumerate(lst[1:], start=1):
if item not in tree_dict.keys():
partent_node = tree_dict[lst[index-1]]
tree_dict[item] = tree.create_node(item, parent=partent_node)
tree.show()