简体   繁体   English

如何在 Python 中存储递归函数的输出?

[英]How to store the output of a recursive function in Python?

I have created a dictionary like so:我创建了一个这样的字典:

d = {1: {3: {}, 4: {6: {}}}, 5: {}}

Then I iterate through all the items and I can do it recursively:然后我遍历所有项目,我可以递归地进行:

def pretty(d, indent=0):
    for key, value in d.items():
        print('\t' * indent + str(key))

        if isinstance(value, dict):
            pretty(value, indent+1)
        else:
            print('\t' * (indent+1) + str(value))

pretty(d)

My goal is to store the output into a string variable in such a way that I can manipulate it.我的目标是以我可以操作的方式将输出存储到字符串变量中。 Therefore the result should be something like this:因此,结果应该是这样的:

msg ="""
1
        3
        4
                6
5
"""

I tried to reach my goal with the following implementation:我试图通过以下实现来达到我的目标:

def pretty(d, indent=0, indent_before=0, msg_old=""):
    for key, value in d.items():
        #print('\t' * indent + str(key) + '({})({})'.format(indent,indent_before))
        msg = msg_old+'\t' * indent + str(key) + '({})({})\n'.format(indent,indent_before)
        if isinstance(value, dict):
            pretty(value, indent+1, indent, msg)
        else:
            print('\t' * (indent+1) + str(value))
    return msg
    
msg = pretty(result)
print(msg)

But the output of my attempt is: None但我尝试的输出是: None

Would you be able to suggest a smart and elegant way to achieve the desired result?您能否提出一种巧妙而优雅的方式来实现所需的结果?

The main problem is that in your recursive call you are discarding the return value (ie calling pretty but not appending the return value to the existing message).主要问题是,在您的递归调用中,您丢弃了返回值(即调用pretty但不将返回值附加到现有消息)。

Here is a solution based closely on your original code.这是一个密切基于您的原始代码的解决方案。

d = {1: {3: {}, 4: {6: {}}}, 5: {}}

def pretty(d, indent=0):
    msg = ''
    for key, value in d.items():
        msg += '\t' * indent + str(key) + '\n'
        if isinstance(value, dict):
            msg += pretty(value, indent+1)  # <=== see how return value is used
        else:
            msg += '\t' * (indent+1) + str(value) + '\n'
    return msg

print(pretty(d))

I know you are trying to implement your own solution but you never mentioned the builtin pprint library/function that does this all for you:我知道您正在尝试实施自己的解决方案,但您从未提到为您完成所有这些工作的内置pprint库/函数:

from pprint import pformat
d = {1: {3: {}, 4: {6: {}}}, 5: {}}
print(pformat(d, indent=0))

{1: {3: {}, 4: {6: {}}}, 5: {}}

If your dict is well-formed, then you can use:如果您的 dict 格式正确,那么您可以使用:

>>> def pretty(d, indent=0):
...     return "".join(["\n" + "\t" * indent + str(k) +
...                     pretty(v, indent + 1) for k, v in d.items()])
...
>>> d = {1: {3: {}, 4: {6: {}}}, 5: {}}
>>> pretty(d)
'\n1\n\t3\n\t4\n\t\t6\n5'
>>> print(pretty(d))

1
        3
        4
                6
5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM