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 循环,但这不是我想要的。
使用递归函数:
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)
出局:莉莉布拉德汤姆吉姆加里史蒂夫