5

我有一个“非标准”形式的字典树,如下所示:

tree = {'0': {'A': {'B': {'C': {}}}},
             {'D': {'E': {}},
                   {'F': {}}}}

叶节点被定义为字典键值对,其中值是一个空字典。我想将所有叶到根路径提取为列表列表,如下所示:

paths_ = [['C', 'B', 'A', '0'],
          ['E', 'D', '0'],
          ['F', 'D', '0']]

如果有帮助,路径也可以反转。

paths_ = [['0', 'A', 'B', 'C'],
          ['0', 'D', 'E'],
          ['0', 'D', 'F']]

我知道我必须递归地执行它,并且我需要每个路径的累加器列表。如果函数产生路径列表也很好。我到目前为止是这样的:

def paths(node, subtree, acc=[]):
    if not subtree:
        yield [node]+acc
    for n, s in subtree.items():
        yield paths(n, s, acc)

它并没有真正做到我想要的:

paths_ = list(paths('0', tree['0']))

理想情况下,这应该返回列表列表。任何帮助都感激不尽。

4

3 回答 3

8

假设您实际上打算使用以下结构tree

tree = {'0': {'A': {'B': {'C': {}}},
              'D': {'E': {},
                    'F': {}}}}

这是一个类似的paths()功能,应该做你想做的事:

def paths(tree, cur=()):
    if not tree:
        yield cur
    else:
        for n, s in tree.items():
            for path in paths(s, cur+(n,)):
                yield path

结果:

>>> list(paths(tree))
[('0', 'A', 'B', 'C'), ('0', 'D', 'E'), ('0', 'D', 'F')]

请注意,我使用元组而不是列表作为默认参数,这是因为可变的默认参数会让您陷入困境

于 2012-07-19T23:23:07.490 回答
2

您可以使用类似于所选答案的内容。

 import collections

 def iter_paths(tree, parent_path=()):
     for path, node in tree.iteritems():
         current_path = parent_path + (path,)
         if isinstance(node, collections.Mapping):
             for inner_path in iter_paths(node, current_path):
                 yield inner_path
         else:
             yield current_path

对于以下字典:

tree = {'A':1, 'B':{'B1':1, 'B2':2}, 'C':{'C1':{'C11':1, 'C12':2},'C2':{'C21':1, 'C22':2}}}

输出应该是(产量顺序可能不同):

('A',)
('C', 'C2', 'C22')
('C', 'C2', 'C21')
('C', 'C1', 'C12')
('C', 'C1', 'C11')
('B', 'B1')
('B', 'B2')
于 2017-02-18T10:08:22.303 回答
0

假设树结构是这种格式: {'0': {'A': {}, 'B': {}}} 那么这样的东西应该可以解决问题。

def paths(nodeId, children, ancestors, allPaths):
    ancestors.append(nodeId)
    if len(children) == 0:
        allPaths.append(ancestors)
    else:
        for childId in children:
            paths(childId, children[childId], ancestors[:], allPaths)

allPaths = []
paths('0', tree['0'], [], allPaths)

像这样的东西应该工作。通常我会先试试这个,但我现在在我的 iPad 上。如果它不起作用,它应该给你一些想法。

于 2012-07-19T23:23:17.677 回答