Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.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 如何使for循环使用由if语句生成的新列表_Python_List_For Loop_If Statement_Nested - Fatal编程技术网

Python 如何使for循环使用由if语句生成的新列表

Python 如何使for循环使用由if语句生成的新列表,python,list,for-loop,if-statement,nested,Python,List,For Loop,If Statement,Nested,这是我的代码: 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循环,但这不是我想要它做的。使用

这是我的代码:

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)
出局:莉莉·布拉德·汤姆·吉姆·加里·史蒂夫


尝试递归你到底想要什么,停止第一个列表上的当前迭代,或者先遍历所有第一个列表,然后再遍历第二个列表?顺便说一句,你的
否则:continue
是多余的。它肯定是多余的!我只是想解决OP的问题,尽量少碰代码,这样OP就能看到与问题相关的实际变化。但是是的,谢谢!是的,很好。我通常也这么做。这只是给未来所有遇到这个答案的读者的一个提示。太好了------