打破 for 循环和 if 条件的混合
Breaking out of a mixture of for loops and if conditions
我有一段代码,其中有几个循环。通过检查条件(使用 if 语句)我想跳出除最后一个循环之外的所有循环。有没有一种方法可以在不修改我的大部分代码的情况下做到这一点,因为我提交它的时间非常少。
for file in dirs:
....
....
#Opens a file in the directory
with open(path, 'rU') as csvfile:
....
....
....
#Iterates over every row in the File
for row in csvreader:
...
#If the data is insufficient, the next row will be iterated.
if len(Parameters)>15:
#If this condition is not satisfied then I need to go to the next iteration of the first 'for' loop
#Without Calculating the Average_Slip
....
....
Calculation_of_Slip()
#Because when all the rows are done iterating, Average_Slip encounters an error as the input values depend on the Slip.
#Instead I need to go to the next file in the directory
Average_slip(Slip_3MW,Slip_7MW,Slip_9MW,Counter_1, Counter_2, Counter_3, Counter_4)
我确定我遗漏了一些非常简单的东西,但任何人都可以帮助我。
基于an answer to a previous similar question:您可以将嵌套循环的代码重构为一个函数,然后用return
打破它。
这也将增加可读性,因为如果层次太多,嵌套的流程控制会变得一团糟。
我有一段代码,其中有几个循环。通过检查条件(使用 if 语句)我想跳出除最后一个循环之外的所有循环。有没有一种方法可以在不修改我的大部分代码的情况下做到这一点,因为我提交它的时间非常少。
for file in dirs:
....
....
#Opens a file in the directory
with open(path, 'rU') as csvfile:
....
....
....
#Iterates over every row in the File
for row in csvreader:
...
#If the data is insufficient, the next row will be iterated.
if len(Parameters)>15:
#If this condition is not satisfied then I need to go to the next iteration of the first 'for' loop
#Without Calculating the Average_Slip
....
....
Calculation_of_Slip()
#Because when all the rows are done iterating, Average_Slip encounters an error as the input values depend on the Slip.
#Instead I need to go to the next file in the directory
Average_slip(Slip_3MW,Slip_7MW,Slip_9MW,Counter_1, Counter_2, Counter_3, Counter_4)
我确定我遗漏了一些非常简单的东西,但任何人都可以帮助我。
基于an answer to a previous similar question:您可以将嵌套循环的代码重构为一个函数,然后用return
打破它。
这也将增加可读性,因为如果层次太多,嵌套的流程控制会变得一团糟。