带条件的python破环
我试图阅读xlsx do文档,找到特定的通道并打印一个区域,但不打印任何通道。当“无”在特定列中时,也打破循环带条件的python破环,python,openpyxl,Python,Openpyxl,我试图阅读xlsx do文档,找到特定的通道并打印一个区域,但不打印任何通道。当“无”在特定列中时,也打破循环 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
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文本。文件格式:。我不能解决这个问题。请原谅本机错误。我是新python,只是在寻找答案。当您检查循环是否为
None
时,您可以调用break
退出内部循环,然后在返回之前进行进一步的逻辑分析。您还可以使用continue
跳过该for循环。有关断开内部循环的示例,请参见下文
榜样;如果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范围for循环):
第二个例子将打破整个方法,从而打破范围内r的
循环。猜测这并不能回答问题,因为它被否决了。我想也许这个问题需要更多的信息让我理解当时被问到的问题。据我所知,它是在问如何打破循环。如果可能的话,你能解释一下我的代码吗?@IanJ Van为你更新了我的答案。如果你需要归还任何东西,你必须弄清楚你想要归还什么。@Celphlin我不需要归还任何东西,但是,如果列中只有一行没有,就打破循环。然后,break
会这样做。你能通过google drive/dropbox包含你的excel文件,并提到你想提取的行吗?@Urielli如果这真的是这里要问的问题,正如他所说的“当特定列中没有行时也打破循环。”那为什么我的回答没有被接受呢?目前它被否决为-1,我本以为它回答了我刚才引用的问题。@Cephlin我不知道你为什么被否决,但这里的标准是不回答这些重复项,而是关闭它们,因此人们将被重定向到完整的对话线程。@Urielli这很公平,但也许他们可以留下一条评论,告诉我这一点,而不是明目张胆地否决一个正确的答案。。。投票否决正确答案似乎有些奇怪。谢谢你让我知道。测试文档
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=" ")