Python 递归调用的问题

Python 递归调用的问题,python,recursion,Python,Recursion,我写了这个函数: 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], li

我写了这个函数:

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

我该如何着手解决这个问题


谢谢大家!

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

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

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)