打破for循环和条件的混合

时间:2015-06-05 05:21:33

标签: python loops control-flow

我有一段代码,里面有几个循环。通过检查条件(使用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)

我确信我错过了一些非常简单的事情,但任何人都可以帮助我。

1 个答案:

答案 0 :(得分:2)

基于an answer to a previous similar question:您可以将嵌套循环重构为函数并将其与return分解。

这也会增加可读性,因为如果有太多级别,嵌套流控制可能会变得一团糟。