[英]Breaking out of one for loop and continuing the other code
I currently have an excel sheet checking another excel sheet for certain numbers.我目前有一个 excel 表,用于检查另一个 excel 表中的某些数字。 Once it finds the matching cell, I want it to move on back to the very first for loop.一旦找到匹配的单元格,我希望它返回到第一个 for 循环。 if it doesn't find the matching cell, but finds the first 6 digits of it, I want it to mark it as checked and then move back to the first for loop again.如果它没有找到匹配的单元格,但找到了它的前 6 位数字,我希望它将其标记为已选中,然后再次移回第一个 for 循环。
How is this done?这是怎么做的?
Below is my code.下面是我的代码。 I commented where I wanted it to go back to the first for
loop I made.我评论了我希望它回到我做的第一个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')
Just use the break
statement.只需使用break
语句。 It breaks you out of a for
loop or while
loop.它使您摆脱for
循环或while
循环。
From the Python docs:来自 Python 文档:
break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. break 只能在语法上嵌套在 for 或 while 循环中发生,但不能嵌套在该循环内的函数或类定义中。 It terminates the nearest enclosing loop , skipping the optional else clause if the loop has one.它终止最近的封闭循环,如果循环有一个可选的 else 子句,则跳过可选的 else 子句。 If a for loop is terminated by break, the loop control target keeps its current value.如果 for 循环被 break 终止,则循环控制目标保持其当前值。 When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.当 break 将控制权从带有 finally 子句的 try 语句中移出时,该 finally 子句在真正离开循环之前执行。
(Emphasis mine) (强调我的)
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.