如何使 for 循环使用由 if 语句创建的新列表

Koo*_*vet 2 python for-loop if-statement nested list

这是我的代码:

the_list = ['Lily', 'Brad', 'Fatima', 'Zining']

for name in the_list:
    print(name)
    if name == 'Brad':
      the_list = ['Tom', 'Jim', 'Garry', 'Steve']
    else:
      continue

Run Code Online (Sandbox Code Playgroud)

如何使 for 循环现在通过新列表运行

我知道我可以在 if 语句中创建一个新的 for 循环,但这不是我想要的。

miq*_*vir 6

使用递归函数:

def check_the_list(x):
    for name in x:
        print(name)
        if name == 'Brad':
            check_the_list(['Tom', 'Jim', 'Garry', 'Steve'])
        else:
            continue


the_list = ['Lily', 'Brad', 'Fatima', 'Zining']

check_the_list(the_list)
Run Code Online (Sandbox Code Playgroud)

出局:莉莉布拉德汤姆吉姆加里史蒂夫法蒂玛齐宁

或在检查其他列表后停止:

def check_the_list(x):
    for name in x:
        print(name)
        if name == 'Brad':
            check_the_list(['Tom', 'Jim', 'Garry', 'Steve'])
            break
        else:
            continue


the_list = ['Lily', 'Brad', 'Fatima', 'Zining']

check_the_list(the_list)
Run Code Online (Sandbox Code Playgroud)

出局:莉莉布拉德汤姆吉姆加里史蒂夫

  • 绝对是!我只是试图解决OP提出的问题,并最少地接触代码,以便OP可以看到与问题相关的实际更改是什么。但是,是的,谢谢! (2认同)