Python 如何在递归函数中只运行一次语句
我想在递归函数中复制列表Python 如何在递归函数中只运行一次语句,python,Python,我想在递归函数中复制列表 def rec(I: List[int]) -> List[int]: new_lst = I[:] # <- want to do this only on first call of rec in recursive stack # ....(new_lst is edited) rec(new_lst) return new_lst def rec(I:List[int])->List[int]: new_lst=I
def rec(I: List[int]) -> List[int]:
new_lst = I[:] # <- want to do this only on first call of rec in recursive stack
# ....(new_lst is edited)
rec(new_lst)
return new_lst
def rec(I:List[int])->List[int]:
new_lst=I[:]#一种解决方案是将其包装在初始值设定项函数中,然后调用该初始值设定项函数:
def rec(I: List[int]) -> List[int]:
....(new_lst is edited)
rec(new_lst)
return new_lst
def startrec(I: List[int]) -> List[int]:
return rec(I[:])
我们可以再添加一个参数
def rec(I:List[int],is_first:bool)->List[int]:
如果你是第一个:
new_lst=I[:]
#编辑新列表
#然后
记录(新记录,错误)
返回新的\u lst
#调用函数
rec(某些列表,正确)
一种方法是保留原始函数rec
,但添加一个新函数,rec将其重新定义为。因此,rec
中的任何语句都将只运行一次
def rec(I:List[int])->List[int]:
new_lst=I[:]#仅在第一次调用时发生
rec=_rec#重新定义rec函数,以便下次调用它时,我们调用_rec
定义记录(I:List[int])->List[int]:
#..(编辑新文件)
记录员(新登记)
返回新的\u lst
您能否简单地将列表的副本传递给函数并避免在函数中复制它?从外面看,rec(一些列表[:])
。你说的“只运行一次”是什么意思?rec()
函数的作用是什么?为什么它需要递归呢?