python - 递归调用的问题

标签 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], 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:] 生成列表的副本。它是一个全新的列表,其中包含原始列表中除第一项之外的所有内容的副本。如果向其中添加元素,这对原始列表没有影响。因此,当您附加到空列表时,只会附加到空列表,而不附加到它之前的任何列表。

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

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)

关于python - 递归调用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9678332/

相关文章:

python - 如何处理 Pandas 中的SettingWithCopyWarning

当 ldap.OPT_X_TLS_REQUIRE_CERT 设置为 ldap.OPT_X_TLS_NEVER 时出现 Python LDAP TLS 错误

python - 从列表中的层次结构创建嵌套字典

python - 如何使用 python 根据另一个列表获取列表中的项目计数?

python - 构建基于 Python Web 的应用程序的选项

python - Shap LSTM (Keras, TensorFlow) ValueError : shape mismatch: objects cannot be broadcast to a single shape

ios - 递归动画无法正常工作

c - Linux 中重写 malloc、free 和 calloc 会导致递归

python - 使用列表打印有向图中的所有路径

C++ unix下递归复制目录