如何在python中的一行if条件中编写多个for循环?(特定于 DOCX)

Rab*_*dra 1 python python-3.x python-docx

我有以下代码。

for row in table.rows:
    for cell in row.cells:
        if cell.tables:
            <some code>
        else:
            <different code>
Run Code Online (Sandbox Code Playgroud)

但我需要将其写在一行中,如下所示,以便 in<different code>else运行一次,而不是由于循环而多次运行。

if any(cell.tables for cell in row.cells for row in table.rows):
    <some code>
else:
    <different code>
Run Code Online (Sandbox Code Playgroud)

然而,这一行在row.cells处显示未解决的引用“行”错误。这个衬垫可以工作,但不知道为什么它在这个 docx 表案例中不起作用。如果除了单行 if 条件之外,是否可以以不同且更好的方式完成此操作,我也欢迎提出建议。

khe*_*ood 6

你的for条款被颠倒了。您试图row在第一for个子句中引用,然后在第二个子句中定义它。这就是为什么它不起作用。

你的意思是

if any(cell.tables for row in table.rows for cell in row.cells):
    ...
Run Code Online (Sandbox Code Playgroud)

  • 像这样的嵌套表达式中的“for”子句需要以与将它们嵌套在缩进代码行中时相同的顺序出现。外部 for 循环先执行,内部再执行,依此类推。这样可以轻松记住所需的顺序:) (4认同)
  • 哇,但这很奇怪。它过去对我有用。但不确定为什么这会按照您建议的方式采用 for 子句。谢谢! (2认同)