python打破循环与条件

时间:2017-01-19 11:47:34

标签: python openpyxl

我正在尝试阅读xlsx做文档,找到特定的通道并打印一个区域,但是没有打印无通道。当"无"在特定栏目中。

def some():
    for r in range(1, ws.max_row):
        for c in range(1, ws.max_column):
            db = ws.cell(row=r, column=c)
            if db.value == 'this one':
                for rows in ws.iter_rows(min_row=r + 1, min_col=c - 1,
                                         max_row=r + 30, max_col=c):
                    for cell in rows:
                        if cell.value is None:
                            if column_index_from_string(db.column) == c:
                                return
                        else:
                            print(cell.value, end=" ")
                    print()

此代码返回唯一的1个通道,然后打破头循环。 的输出: 1315 text
文件格式:https://drive.google.com/file/d/0B_bbUxPgcVESVGstWWRxV3k4emM/view。我无法解决这个问题。请原谅原生错误。我是新的python,只是在寻找答案。

1 个答案:

答案 0 :(得分:0)

当您检查周期为None时,您可以调用break退出内循环,然后在返回之前获得更多逻辑,而不是返回。您也可以使用continue跳过for循环。有关打破内循环的示例,请参见下文。

实施例;如果for cell in rows:cell.value,则会停止None循环:

for r in range(1, ws.max_row):
    for c in range(1, ws.max_column):
        db = ws.cell(row=r, column=c)
        if db.value == 'My specific Value':
            for rows in ws.iter_rows(min_row=r+1, min_col=c-1, max_row=r+30, max_col=c):
                for cell in rows:
                    if cell.value is None:
                        if column_index_from_string(db.column) == c:
                            rtn = 1
                            break
                    else:
                        print(cell.value, end=" ")
                print()

return rtn

第二个示例基于外部for循环的中断(循环的r范围):

def print_while_cell_is_not_none():
    for r in range(1, ws.max_row):
        for c in range(1, ws.max_column):
            db = ws.cell(row=r, column=c)
            if db.value == 'My specific Value':
                for rows in ws.iter_rows(min_row=r + 1, min_col=c - 1,
                                         max_row=r + 30, max_col=c):
                    for cell in rows:
                        if cell.value is None:
                            if column_index_from_string(db.column) == c:
                                return
                        else:
                            print(cell.value, end=" ")

第二个例子将破坏整个方法,从而打破for r in range for循环。

相关问题