【问题标题】:Recurse through dictionary of dictionaries, always starting from the top递归遍历字典,总是从顶部开始
【发布时间】:2014-04-17 16:14:00
【问题描述】:

我有以下字典,层次深度未知:

dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}

我发现 the following useful 用于学习如何递归它,但我在修改代码以获得我想要的东西时遇到了麻烦,这是从顶层到顶层的所有路径的列表死胡同。

想要的输出是:

list = ['a,b,c', 'a,b,d', 'a,b,e', 'f,g']

为了开始解决这个问题,我使用了DFS 方法:

hierarchy = []
for parent in dict_of_dicts:
    recurse_dicts(concepts, parent, hierarchy)

def recurse_dicts(concepts, parent, hierarchy):
    hierarchy.append(parent)
    for child in concepts[parents]:
        if len(recurse[node][child].keys()) > 0:
            recurse_dicts(recurse[node], child, hierarchy)
        else:
            return

这导致:

hierarchy = ['a', 'b', 'c', 'd', 'e']

这是一些东西,但不是我想要的。

【问题讨论】:

  • 这可能吗? 是的。请给我 200 美元! (对不起)。
  • 这听起来像是 DFS 的工作。
  • 您能否编辑问题并描述您遇到的问题?

标签: python recursion dictionary


【解决方案1】:

假设您的值是 always 字典,您可以使用:

def paths(d, path=(), res=None):
    if res is None:
        res = []
    for key, value in d.iteritems():
        if not value:
            # end of the line, produce path
            res.append(','.join(path + (key,)))
        else:
            # recurse down to find the end of this path
            paths(value, path + (key,), res)
    return res

这使用一个共享列表(在第一次调用时生成)将生成的路径传递回调用者,并为每个递归步骤构建一个路径,以便在遇到空值时将其添加到结果列表中。

演示:

>>> dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}
>>> paths(dict_of_dicts)
['a,b,c', 'a,b,e', 'a,b,d', 'f,g']

路径没有排序,因为字典没有顺序;如果需要,您仍然可以对键进行排序:

for key in sorted(d):
    value = d[key]

而不是 for key, value in d.iteritems() 循环。

【讨论】:

    【解决方案2】:

    这是一个跟踪每个分支路径的递归 DFS 过程:

    dict_of_dicts = {'a': {'b': {'c': {}, 'd': {}, 'e': {}}}, 'f': {'g': {}}}
    
    def dfs(path, d):
        if d == {}:
            print path;
        for item in d:
            dfs(path+[item],d[item])
    
    dfs([],dict_of_dicts)
    

    输出:

    ['a', 'b', 'c']
    ['a', 'b', 'e']
    ['a', 'b', 'd']
    ['f', 'g']
    

    【讨论】:

      猜你喜欢
      • 2013-03-04
      • 2023-03-29
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 2011-04-21
      相关资源
      最近更新 更多