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 条件之外,是否可以以不同且更好的方式完成此操作,我也欢迎提出建议。
你的for条款被颠倒了。您试图row在第一for个子句中引用,然后在第二个子句中定义它。这就是为什么它不起作用。
你的意思是
if any(cell.tables for row in table.rows for cell in row.cells):
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7133 次 |
| 最近记录: |