我很难弄清楚如何从递归函数返回嵌套列表。我有一个嵌套的结构,我想从中返回每个级别的元素。
我的结构类似于以下内容,但是我不知道深度。
# 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
答案 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']]