簡體   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