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

时间:2019-10-03 08:01:29

标签: python list dictionary recursion nested

问题

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

输入

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

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

输出

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

# Desired output
[['a'], ['b'], ['c'], ['a', 'd'], ['a', 'e'], ['a', 'f'], ['a', 'f', 'g']]

我尝试过的

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

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

3 个答案:

答案 0 :(得分:5)

您可以这样做:

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

输出

import pandas as pd
import re

Keywords = [

"Caden(S, A)",
"Caden(a",
"Caden(.A))",
"Caden.Q",
"Caden.K",
"Caden"
]

data = {'People' : ["Caden(S, A) Charlotte.A, Caden.K;", "Emily.P Ethan.B; Caden(a", "Grayson.Q, Lily; Caden(.A))", "Mason, Emily.Q Noah.B; Caden.Q - Riley.P"]}

df = pd.DataFrame(data)

pat = '|'.join(r"\b{}\b".format(x) for x in Keywords)

df["found"] = df['People'].str.findall(pat).str.join('; ')

print df["found"]

答案 1 :(得分:2)

我们可以做这样的事情:

dictionary = {
    'a': {
        'd': None, 
        'e': None, 
        'f': {
            'g': None,
        },
    }, 
    'b': None, 
    'c': None,
}
expected_output = [
    ['a'], ['b'], ['c'], 
    ['a', 'd'], ['a', 'e'], ['a', 'f'], 
    ['a', 'f', 'g'],
]


def get_levels(dictionary, parents=[]):
    if not dictionary:
        return []

    levels = []

    for key, val in dictionary.items():
        cur_level = parents + [key]
        levels.append(cur_level)
        levels.extend(get_levels(val, cur_level))

    return levels


output = get_levels(dictionary)
print(output)
assert sorted(output) == sorted(expected_output)

答案 2 :(得分:0)

使用yield的递归方法略短:

my_input = {'a': {'d':None, 'e':None, 'f':{'g':None}}, 'b':None, 'c':None}
def get_paths(d, c = []):
  for a, b in getattr(d, 'items', lambda :[])():
     yield c+[a]
     yield from get_paths(b, c+[a])

print(list(get_paths(my_input)))

输出:

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