【发布时间】:2019-06-17 18:15:01
【问题描述】:
我有一个嵌套列表,如下所示:
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”)(当我在一个列表中有很多列表时)。
- “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()
【问题讨论】:
标签: python python-3.x tree treeview anytree