我有一个类似于以下内容的嵌套列表:
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。我读了很多文章,尝试了许多不同的方法,但没有使它起作用。
更新:
我想出了以下方法,但现在遇到的问题是
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()
答案 0 :(得分:1)
我调查了anytree
并提出了这个建议:
from anytree import Node, RenderTree
lst = [["a", "b", "c", "e"], ["a", "b", "f"], ["a", "b", "c", "g", "h"], ["a", "i"]]
def list_to_anytree(lst):
root_name = lst[0][0]
root_node = Node(root_name)
nodes = {root_name: root_node} # keeping a dict of the nodes
for branch in lst:
assert branch[0] == root_name
for parent_name, node_name in zip(branch, branch[1:]):
node = nodes.setdefault(node_name, Node(node_name))
parent_node = nodes[parent_name]
if node.parent is not None:
assert node.parent.name == parent_name
else:
node.parent = parent_node
return root_node
anytree = list_to_anytree(lst)
for pre, fill, node in RenderTree(anytree):
print(f"{pre}{node.name}")
这里没有发生太多事情。我只是将您的列表转换为anytree节点(并且assert
列表表示在执行此操作时是有效的)。并且保留了nodes
中已经有的节点的字典。
输出确实是
a
├── b
│ ├── c
│ │ ├── e
│ │ └── g
│ │ └── h
│ └── f
└── i
如果有多个同名节点,则不能使用上面的dict
;您需要从子节点的根节点进行迭代:
def list_to_anytree(lst):
root_name = lst[0][0]
root_node = Node(root_name)
for branch in lst:
parent_node = root_node
assert branch[0] == parent_node.name
for cur_node_name in branch[1:]:
cur_node = next(
(node for node in parent_node.children if node.name == cur_node_name),
None,
)
if cur_node is None:
cur_node = Node(cur_node_name, parent=parent_node)
parent_node = cur_node
return root_node
您的示例
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"],
]
anytree = list_to_anytree(lst)
for pre, fill, node in RenderTree(anytree):
print(f"{pre}{node.name}")
然后给出:
a
├── b
│ └── e
├── f
│ └── e
└── h
└── i i i