Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在递归函数中只运行一次语句_Python - Fatal编程技术网

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()
函数的作用是什么?为什么它需要递归呢?