如何在python中处理递归?

时间:2014-04-16 10:20:34

标签: python recursion

在互联网上的示例中绘制了一个小函数,但是递归存在问题......

def toSimpleXml(data, wrap = False):
    result = list()
    input_data_type = type(data)
    if input_data_type is list:
        for sub_element in data:
            result.append(toSimpleXml(sub_element))
        return ''.join(result)
    elif input_data_type is dict:
        for tag_name in data:
            sub_element = data[tag_name]
            result.append('<%s>' % tag_name)
            result.append(toSimpleXml(sub_element))
            result.append('</%s>' % tag_name)
        return ''.join(result)

    if wrap:
        return '<%s>%s</%s>' % (wrap, data, wrap)

    return data

data = [{'element_1': 'value_1'}, {'element_2': {'element_2_1': 'value_2_1'}}, {'element_1': 'value_1'}]
print toSimpleXml(data, 'root')

根据想法结果应该包含root,但wrap变量为false ...

1 个答案:

答案 0 :(得分:3)

该函数返回太早wrap即可发挥作用。设置data而不是返回:

def toSimpleXml(data, wrap = False):
    result = list()
    input_data_type = type(data)
    if input_data_type is list:
        for sub_element in data:
            result.append(toSimpleXml(sub_element))
        data = ''.join(result)
    elif input_data_type is dict:
        for tag_name in data:
            sub_element = data[tag_name]
            result.append('<%s>' % tag_name)
            result.append(toSimpleXml(sub_element))
            result.append('</%s>' % tag_name)
        data = ''.join(result)

    if wrap:
        return '<%s>%s</%s>' % (wrap, data, wrap)

    return data

现在实际上已达到if wrap语句:

>>> print toSimpleXml(data, 'root')
<root><element_1>value_1</element_1><element_2><element_2_1>value_2_1</element_2_1></element_2><element_1>value_1</element_1></root>