【问题标题】:Breaking out of one for loop and continuing the other code跳出一个 for 循环并继续其他代码
【发布时间】:2016-09-12 14:37:17
【问题描述】:

我目前有一个 excel 表检查某些数字的另一个 excel 表。一旦找到匹配的单元格,我希望它返回到第一个 for 循环。如果它没有找到匹配的单元格,但找到了它的前 6 位数字,我希望它将其标记为已检查,然后再次移回第一个 for 循环。

这是怎么做到的?

下面是我的代码。我评论了我希望它回到我创建的第一个 for 循环的位置。

for row in range(sheet.nrows):
    cell = str(sheet.cell_value(row, 0))
    if fd.match(cell):
        for rows in range(sheet.nrows):
            windcell = str(windc_sheet.cell_value(rows, 0))
            if fd.match(windcell):
                if cell == windcell:
                    outputsheet.write(row, 1, ' ')
                    #GO BACK TO FIRST FOR LOOP

                else:
                    sixdig = cell[0:6]
                    sixdigwind = windcell[0:6]
                    if sixdig == sixdigwind:
                        outputsheet.write(row, 1, 'Check')
                        #GO BACK TO FIRST FOR LOOP

    else:
        sixdig = cell[0:6]
        for rows in range(sheet.nrows):
            windcell = str(windc_sheet.cell_value(rows,0))
            sixdigwind = windcell[0:6]
            if sixdig == sixdigwind:
                outputsheet.write(row, 1, 'Check')

【问题讨论】:

  • 使用break 语句。
  • 使用运算符中断
  • 您希望在哪里继续执行? “移动”或“返回”到“先换”有点不清楚。

标签: python for-loop break


【解决方案1】:

只需使用break 语句。它会让你脱离for 循环或while 循环。

来自 Python 文档:

break 只能在语法上嵌套在 for 或 while 循环中,但不能 嵌套在该循环内的函数或类定义中。 它终止 最近的封闭循环,如果循环有一个,则跳过可选的 else 子句。 如果 for 循环被 break 终止,则循环控制目标保持其当前 价值。当 break 将控制权从带有 finally 子句的 try 语句中传递出去时, finally 子句在真正离开循环之前执行。

(强调我的)

for row in range(sheet.nrows):
    cell = str(sheet.cell_value(row, 0))
    if fd.match(cell):
        for rows in range(sheet.nrows):
            windcell = str(windc_sheet.cell_value(rows, 0))
            if fd.match(windcell):
                if cell == windcell:
                    outputsheet.write(row, 1, ' ')
                    break  # TERMINATE ENCLOSING FOR LOOP

                else:
                    sixdig = cell[0:6]
                    sixdigwind = windcell[0:6]
                    if sixdig == sixdigwind:
                        outputsheet.write(row, 1, 'Check')
                        break  # TERMINATE ENCLOSING FOR LOOP

    else:
        sixdig = cell[0:6]
        for rows in range(sheet.nrows):
            windcell = str(windc_sheet.cell_value(rows,0))
            sixdigwind = windcell[0:6]
            if sixdig == sixdigwind:
                outputsheet.write(row, 1, 'Check')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    相关资源
    最近更新 更多