这是我写的功能:
def print_dict(d, indent, CMD_str, index = 0):
if isinstance(d,dict):
for key, value in d.items():
CMD_str += ('\t' * indent + str(key) + '\n')
# print('\t' * indent + str(key) + '\n')
if isinstance(value, dict):
CMD_str += print_dict(value, indent+1, CMD_str, index = index+1)
elif isinstance(value,list):
for i in value:
if isinstance(i,list):
CMD_str += print_dict(i,indent+1, CMD_str = CMD_str, index = index+1)
else:
CMD_str += ('\t'*(indent+1) + i + '\n')
else:
CMD_str += ('\t' * (indent+1) + str(value) + '\n')
elif isinstance(d,list):
for i in d:
print(index)
if isinstance(i,list):
CMD_str += print_dict(i,indent+1, CMD_str, index = index+1)
else:
CMD_str += ('\t'*(indent) + i)
return CMD_str
这个功能最初打印字典并且工作得很好。但是,我现在需要它输出一个字符串而不是打印,所以我添加了CMD_str输入参数,所以我可以继续将字符串传递给函数,直到我通过字典。然而,它被卡在某处,我无法弄清楚原因。通过打印缩进值,我可以看出它在卡住之前会运行大约10次。任何帮助将不胜感激。
答案 0 :(得分:0)
您的递归函数中有一些重复的代码,为了清晰起见可以重新组织,以减少错误发生的可能性。这是一个例子:
tab = " "
def print_dict(d, indent):
result = []
for key, value in d.items():
result.append(tab*indent + str(key))
result.append(print_obj(value, indent+1))
return '\n'.join(result)
def print_list(a, indent):
result = []
for value in a:
result.append(print_obj(value, indent))
return '\n'.join(result)
def print_obj(obj, indent):
result = ""
if type(obj) is dict:
result = print_dict(obj, indent)
elif type(obj) is list:
result = print_list(obj, indent)
else:
result = tab*indent + str(obj)
return result
d = {
'key1': ['val1', 'val2', {'key3':'val3'}],
'key4': 'val5',
'key5': {
'key6': 'val6',
'key7': [1, 2, 3, 4]
}
}
import pprint
pprint.pprint(d, width=1)
print print_obj(d, 0)
输出
{'key1': ['val1',
'val2',
{'key3': 'val3'}],
'key4': 'val5',
'key5': {'key6': 'val6',
'key7': [1,
2,
3,
4]}}
key1
val1
val2
key3
val3
key5
key7
1
2
3
4
key6
val6
key4
val5
答案 1 :(得分:0)
from numbers import Number
def recursive_print(item, level=0):
result = ''
indent = '\t' * level
if isinstance(item, dict):
result += '\n'.join(
indent + str(key) + '\n' +
recursive_print(value, level+1)
for (key, value) in item.items()
)
elif isinstance(item, list):
def one_line_printable(x): return isinstance(x, str) or isinstance(x, Number)
if all(one_line_printable(element) for element in item):
result += indent + '\t'.join(str(element) for element in item)
else:
result += '\n'.join(recursive_print(element, level) for element in item)
else:
result += indent + str(item)
return result
请注意,该函数应该在每次调用时处理它的缩进。但是,在文本返回的字符串不以'\n'
结尾后,调用者应该提供'\n'
。