📜  如何在Python跳出多个循环?

📅  最后修改于: 2022-05-13 01:55:47.409000             🧑  作者: Mango

如何在Python跳出多个循环?

在本文中,我们将看到如何在Python跳出多个循环。例如,我们得到一个列表 arr 和一个整数 x。任务是按顺序遍历每个嵌套列表并继续显示元素,直到找到等于 x 的元素。如果找到这样的元素,则会显示一条适当的消息,并且代码必须停止显示更多元素。

Input: arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], x = 6
Output:
1
2
3
Element found
Input: arr = [[10, 20, 30], [40, 50, 60, 70]], x = 50
Output:
10
20
30
40
Element found

解决此问题的直接方法是使用 for 循环遍历 arr 的所有元素,并使用嵌套的 for 循环遍历 arr 中每个嵌套列表的所有元素并继续打印它们。如果遇到等于 x 的元素,则会显示相应的消息,并且代码必须跳出这两个循环。

但是,如果我们简单地使用单个 break 语句,代码只会终止内循环,外循环将继续运行,这是我们不希望发生的。

Python3
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x:
            if j == x:
                print('Element found')
                break
            else:
                print(j)
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


Python3
# Python code to break out of
# multiple loops by defining a
# function and using return statement
 
 
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x and returning
            # the function if such element is found
            # else printing the element:
            if j == x:
                print('Element found')
                return
            else:
                print(j)
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


Python3
# Python code to break out of multiple
# loops by using an else block
 
 
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x:
            if j == x:
                print('Element found')
                break
            else:
                print(j)
                 
        # If the inner loop completes without encountering
        # the break statement then the following else
        # block will be executed and outer loop will
        # continue to the next value of i:
        else:
            continue
             
        # If the inner loop terminates due to the
        # break statement, the else block will not
        # be executed and the following break
        # statement will terminate the outer loop also:
        break
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


Python3
# Python code to break out of multiple
# loops by using a flag variable
 
 
def elementInArray(arr, x):
    flag = False  # Defining the flag variable
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x
            # and assigning True value to
            # flag if the condition is met
            # else printing the element j:
            if j == x:
                flag = True
                print('Element found')
                break
            else:
                print(j)
                 
        # If the inner loop terminates due to
        # the break statement and flag is True
        # then the following if block will
        # be executed and the break statement in it
        # will also terminate the outer loop. Else,
        # the outer loop will continue:
        if flag == True:
            break
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


输出:

1
2
3
Element found
7
8
9

在上面的例子中,只要找到 4,break 语句就终止了内循环,并且跳过了同一个嵌套列表 (5, 6) 的所有其他元素,但代码没有终止外循环然后继续下一个嵌套列表并打印其所有元素。



方法一:使用return语句

定义一个函数并将循环放置在该函数。使用return语句可以直接结束函数,从而跳出所有循环。

蟒蛇3

# Python code to break out of
# multiple loops by defining a
# function and using return statement
 
 
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x and returning
            # the function if such element is found
            # else printing the element:
            if j == x:
                print('Element found')
                return
            else:
                print(j)
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)

输出:

1
2
3
Element found

方法 2:使用 else: continue

一种更简单的方法是在内循环后使用包含 continue 语句的 else 块,然后在外循环内的 else 块后添加 break 语句。如果内部循环由于内部循环中给出的 break 语句而终止,则内部循环之后的 else 块将不会被执行,else 块之后的 break 语句也将终止外部循环。另一方面,如果内循环在没有遇到任何 break 语句的情况下完成,那么包含 continue 语句的 else 块将被执行,外循环将继续运行。即使循环次数增加,想法也是一样的。

蟒蛇3

# Python code to break out of multiple
# loops by using an else block
 
 
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x:
            if j == x:
                print('Element found')
                break
            else:
                print(j)
                 
        # If the inner loop completes without encountering
        # the break statement then the following else
        # block will be executed and outer loop will
        # continue to the next value of i:
        else:
            continue
             
        # If the inner loop terminates due to the
        # break statement, the else block will not
        # be executed and the following break
        # statement will terminate the outer loop also:
        break
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)

输出:

1
2
3
Element found

方法 3:使用标志变量

打破多个循环的另一种方法是使用 False 值初始化标志变量。可以在中断内部循环之前为变量分配一个 True 值。外循环必须在内循环之后包含一个 if 块。 if 块必须检查标志变量的值并包含一个 break 语句。如果标志变量为 True,则 if 块将被执行并且也将跳出内部循环。否则,外循环将继续。

蟒蛇3

# Python code to break out of multiple
# loops by using a flag variable
 
 
def elementInArray(arr, x):
    flag = False  # Defining the flag variable
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x
            # and assigning True value to
            # flag if the condition is met
            # else printing the element j:
            if j == x:
                flag = True
                print('Element found')
                break
            else:
                print(j)
                 
        # If the inner loop terminates due to
        # the break statement and flag is True
        # then the following if block will
        # be executed and the break statement in it
        # will also terminate the outer loop. Else,
        # the outer loop will continue:
        if flag == True:
            break
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)

输出:

1
2
3
Element found