gpt4 book ai didi

python - 递归调用的问题

转载 作者:行者123 更新时间:2023-11-30 23:45:13 26 4
gpt4 key购买 nike

我写了这个函数:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com