确保递归调用期间某个操作仅发生一次

The*_*One 2 python recursion

我有一个过程,其中包含一个涉及递归调用该过程的步骤。我希望某个操作不第一次执行,而是在其他时候递归调用。

def a(string):
    while string.startswith('/'):
        string =string[1:]
    stringa = string.split('/',1)

    if(len(stringa)>1):
        a(stringa)
Run Code Online (Sandbox Code Playgroud)

基本上我的字符串是类型/a/b/c/d。我希望{/}{a/b/c/d}第一次有 stringa ,连续递归为
stringa ={a}{b/c/d}
stringa ={b}{c/d}
stringa ={c}{d}

Bry*_*ley 7

基本模式是使用标志。您可以将标志设置为默认参数,这样您就不必在第一次调用函数时传递它,然后函数在递归调用时设置(或取消设置...)标志。

它看起来像这样:

def some_function(..., is_first=True):
    if is_first:
        # code to run the first time
    else
        # code to run the other times
    # recurse
    some_function(..., is_first=False)
Run Code Online (Sandbox Code Playgroud)

我不知道如何将其转换为您的代码,因为仅在第一次时才不清楚您想要做什么。另外,您首先传递一个字符串,但您的递归调用传递一个列表。