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

这是我的代码:

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

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

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

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

回答

使用递归函数:

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)

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

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

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)

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

  • it definetely is! I just tried to solve the question the OP had, and touch the code the least so that OP can see what is the actual change relevant to the question. But yes, thx!

以上是如何使for循环使用由if语句创建的新列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>