递归函数中的默认列表值

时间:2016-09-30 21:47:15

标签: python recursion

以下函数在每次运行时都会保留其列表中的值。由于使用了可变的默认参数,我最近作为Python 'gotcha'了解了这个问题。

我该如何解决?在函数外部创建全局变量会导致同样的问题。将列表传递给函数会中断递归,并仅显示第一级别的类别。

def build_category_list(categories, depth=0, items=[]):
    '''Builds category data for parent select field'''
    for category in categories:
        items.append((category.id, '-' * depth + ' ' + category.name))
        if category.children:
            build_category_list(category.children, depth + 1)
    return items

2 个答案:

答案 0 :(得分:2)

无需在递归函数中传递列表,只需将后续调用的结果连接到当前列表:

def build_category_list(categories, depth=0):
    '''Builds category data for parent select field'''
    items = []
    for category in categories:
        items.append((category.id, '-' * depth + ' ' + category.name))
        if category.children:
            items += build_category_list(category.children, depth + 1)
    return items

答案 1 :(得分:1)

传入列表或通过检查空值可以解决问题。但是你需要将列表传递给递归:

def build_category_list(categories, depth=0, items=None):
    if not items:
        items = []
    '''Builds category data for parent select field'''
    for category in categories:
        items.append((category.id, '-' * depth + ' ' + category.name))
        if category.children:
            build_category_list(category.children, depth + 1, items)
                                                              ^^^^^
    return items

或者,使用返回值来构建答案 - 我的偏好见Antoine的答案......

相关问题