gpt4 book ai didi

追加列表中的 Python 递归

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:06 25 4
gpt4 key购买 nike

我想递归地附加到一个列表,但我想不出一个有效的函数。该函数有两个参数 timesdatatimes应该是附加数据的次数。

到目前为止,这是我的代码:

def replicate_recur(times, data):
result2 = []
if times == 0:
result2.append(data)
else:
result2.append(data)
replicate_recur(times - 1, data)
return result2

最佳答案

您可以使用中间列表附加到每个递归调用中。这避免了您当前遇到的这些重新定义问题:

def replicate_recur(times, data, result=None):
if result is None: # create a new result if no intermediate was given
result = []
if times == 1:
result.append(data)
else:
result.append(data)
replicate_recur(times - 1, data, result) # also pass in the "result"
return result

调用时:

>>> replicate_recur(4, 2)
[2, 2, 2, 2]

关于追加列表中的 Python 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42388155/

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