从路径名创建树形结构。

6
这可能非常简单,但我不确定该怎么做。 在Python中,我想遍历一个列表,比如:
full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]

并获得一个带有基于这些标签的一种树形结构的字典,就像这样:

dictionary = {"A:{"A":["A", "B"], "C":["B"]},"B":{"B":["B]}} 

但我不确定该如何做。我意识到需要使用一些嵌套的for循环。我知道Python中有split()函数。


1
请更新您的问题,并附上您尝试过的代码。 - quamrana
你知道所有的输入都会有相同的“深度”吗?你的所有示例都是3层,但是你是否需要处理像“A/B”这样的内容?具体而言,dictionary["A"]的结果会是什么样子?是字典还是列表? - Nathan Werth
是的,所有示例都将是深度为3。 - Ada
2个回答

2
您可以使用collections.defaultdict与递归结合使用:
from collections import defaultdict
def to_tree(data):
   d = defaultdict(list)
   for a, *b in data:
      d[a].append(b)
   return {a:[i for [i] in b] if all(len(i) == 1 for i in b) else to_tree(b)  
           for a, b in d.items()}

full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]
result = to_tree([i.split('/') for i in full_list])

输出:

{'A': {'A': ['A', 'B'], 'C': ['B']}, 'B': {'B': ['B']}}

0
将叶节点列表条目设置为非空字典,会使得这个过程更加棘手,我认为应该重新考虑这个方面。
>>> full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]
>>> from collections import defaultdict
>>> dictionary = defaultdict(lambda: defaultdict(list))
>>> for entry in full_list:
...     node = dictionary
...     for path in entry.split("/"):
...         if isinstance(node, dict):
...             node = node[path]
...         else:
...             node.append(path)
...
>>> dictionary
defaultdict(<function <lambda> at 0x000001C8098171F0>, {'A': defaultdict(<class 'list'>, {'A': ['A', 'B'], 'C': ['B']}), 'B': defaultdict(<class 'list'>, {'B': ['B']})})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接