我有一个巨大的深度字典,它代表森林(许多非二叉树),我要处理森林并创建具有森林的所有可能关系的文本文件,例如给定字典:
{'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}
生成的文本文件如下所示:
a b c
a b d
a g
请注意,嵌套字典很大,并且递归地对其进行迭代会导致内存运行时错误。
我尝试做的是将字典递归转换为列表列表,这会产生运行时错误。代码:
def return_list(forest):
for ent in forest.keys():
lst = [new_ent] + grab_children(forest[ent])
yield lst
def grab_children(father):
local_list = []
for key, value in father.items():
local_list.append(new_key)
local_list.extend(grab_children(value))
return local_list
错误:“在比较中超过了最大递归深度” RuntimeError
答案 0 :(得分:3)
def l(d):
return '\n'.join(k + (i and ' ' + i) for k, v in d.items() for i in l(v).split('\n'))
print(l({'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}))
这将输出:
a b c
a b d
a g
答案 1 :(得分:3)
无递归,带有生成器和蹦床(写入文件):
data = {'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}
def write_dict(d, s=(), f_out=None):
if len(d) == 0:
if f_out:
f_out.write(' '.join(s) + '\n')
return
for k, v in reversed(list(d.items())):
yield write_dict, v, s + (k, ), f_out
with open('data_out.txt', 'w') as f_out:
stack = [write_dict(data, f_out=f_out)]
while stack:
try:
v = next(stack[-1])
except StopIteration:
del stack[-1]
continue
stack.insert(-1, v[0](v[1], v[2], v[3]))
文件包含:
a b c
a b d
a g
答案 2 :(得分:1)
非递归方法:
d = {'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}
p = q = []
while True:
for k, v in d.items():
if v:
q.append((v, p + [k]))
else:
print(' '.join(p + [k]))
if not q:
break
d, p = q.pop(0)
这将输出:
a g
a b c
a b d