递归调用问题

2024-04-26 23:10:41 发布

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

我写了这个函数:

def append_to_all(L, v):
    '''Append value v, which may be of any type, to all the nested lists in L.
    L is a list, and may contain other lists.'''

        if len(L) == 0:
            return L.append(v)
        elif isinstance(L[0], list):
            L[0].append(v)
            return append_to_all(L[1:], v)
        else:
            return append_to_all(L[1:], v)

if __name__ == '__main__':
    L = [1, 2, [3]]
    append_to_all(L, 'a')
    print L # should return [1, 2, [3, 'a'], 'a']

函数返回[1,2,[3,'a']],而不是[1,2,[3,'a'],'a']。我试过调试,但它找不出错误。似乎当len(L)==0函数被调用时,“a”被追加到空列表中,而不是全局L中

我该怎么解决这个问题?你知道吗

谢谢你!你知道吗


Tags: to函数whichlenreturnifvaluedef
1条回答
网友
1楼 · 发布于 2024-04-26 23:10:41

L[1:]生成列表的副本。这是一份全新的清单,除了第一项外,所有的东西都有副本。如果向其中添加元素,则对原始列表没有影响。因此,当您附加到空列表时,它只附加到空列表,而不是它前面的任何列表。你知道吗

为了递归地执行此操作,您不应该附加到列表,而应该返回新列表

def append_to_all(L, v):
'''Append value v, which may be of any type, to all the nested lists in L.
L is a list, and may contain other lists.'''

    if len(L) == 0:
        return [v]
    elif isinstance(L[0], list):
        return [L[0] + [v]] + append_to_all(L[1:], v)
    else:
        return [L[0]] + append_to_all(L[1:], v)

但这并不是使用递归的地方。迭代解法更简单、更有效。你知道吗

def append_to_all(L, v):
    for item in L:
        if isinstance(L, list):
            item.append(v)
    L.append(v)

相关问题 更多 >