【问题标题】:How to pause a nested for loop and then continue that loop when it is run again?如何暂停嵌套的 for 循环,然后在再次运行时继续该循环?
【发布时间】:2023-01-07 00:22:11
【问题描述】:

我正在做的整个项目是,我使用 openpxyl 从 excel 文档中的特定行和列中获取值,并在网页上填写表格。我填写表格,然后保存,然后填写下一张表格excel 文档中的下一行值。

Excel 看起来像这样:

First Name         Last Name         DOB

George             Hill              9/9/99
Sam                Genius            8/8/88
Bill               Smith             7/7/77

我的其中一行代码:

#First for loop is to run once for each of the three forms I want to fill out
    for i in range(3):
        for row in ws.iter_rows(min_row=1, min_col=1, max_row=3, max_col=1):
            for cell in row:
              print(cell.value)
            
              break
        break  # Tried to use breaks to break the loop so it only prints once for each loop

 

这打印:

George
George
George

现在我知道这是行不通的,因为循环的结构方式。我该如何解决这个问题以便打印:

George             
Sam                
Bill 

【问题讨论】:

    标签: python excel openpyxl nested-loops


    【解决方案1】:

    我不知道我是否正确理解了你的问题,但是如果你想要的结果是第一行的 i 等于 0,第二行的 1 等等,你可以使用 enumerate() 函数用一个这样的 for 循环:

    for i, row in enumerate(ws.iter_rows(min_row=1, min_col=1, max_row=3, max_col=1)):
        print(i, end=' ')
        for cell in row:
            print(cell.value)
    

    这将打印出:

    0 George             
    1 Sam                
    2 Bill 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多