Python:从递归函数返回列表列表

Esb*_*rdt 0 python recursion dictionary nested list

问题

我很难弄清楚如何从递归函数返回嵌套列表。我有一个嵌套的结构,我想从中返回每个级别的元素。

输入项

我的结构类似于以下内容,但是我不知道其深度。

# Data
my_input = {'a': {'d':None, 'e':None, 'f':{'g':None}}, 'b':None, 'c':None}
Run Code Online (Sandbox Code Playgroud)

输出量

我需要将所有可能的级别输出到列表列表

# Desired output
[['a'], ['b'], ['c'], ['a', 'd'], ['a', 'e'], ['a', 'f'], ['a', 'f', 'g']]
Run Code Online (Sandbox Code Playgroud)

我尝试过的

此功能根本不起作用。看来我无法理解如何从递归函数返回。每当我运行该函数时,最终要么覆盖输出,要么没有上一次迭代中的正确信息。关于如何正确编写此功能的任何建议?

def output_levels(dictionary, output=None):
    print(dictionary)
    if not output:
        output = []
    if len(dictionary.keys()) == 1:
        return output.append(dictionary.keys())
    for key in dictionary.keys():
        if not dictionary[key]:
            output.append(key)
            continue
        output.append(output_levels(dictionary[key], output.append(key)))
    return output
Run Code Online (Sandbox Code Playgroud)

Dan*_*ejo 5

您可以这样做:

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


def paths(d, prefix=None):

     if prefix is None:
         prefix = []

     for key, value in d.items():
         if value is not None:
             yield prefix + [key]
             yield from paths(value, prefix=prefix + [key])
         else:
             yield prefix + [key]


print(sorted(paths(my_input), key=len))
Run Code Online (Sandbox Code Playgroud)

输出量

[['a'], ['b'], ['c'], ['a', 'd'], ['a', 'e'], ['a', 'f'], ['a', 'f', 'g']]
Run Code Online (Sandbox Code Playgroud)