繁体   English   中英

跳出一个 for 循环并继续另一个代码

[英]Breaking out of one for loop and continuing the other code

我目前有一个 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语句。 它使您摆脱for循环或while循环。

来自 Python 文档:

break 只能在语法上嵌套在 for 或 while 循环中发生,但不能嵌套在该循环内的函数或类定义中。 它终止最近的封闭循环,如果循环有一个可选的 else 子句,则跳过可选的 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM