递归函数中的默认列表值

2024-04-28 05:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的函数每次运行时都会保留其列表中的值。我最近作为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

Tags: 函数build列表for参数defitems类别
2条回答

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

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的答案。。。你知道吗

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

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

相关问题 更多 >