如何在python中的if条件的一行中写多个for循环? (特定于 DOCX)
How to write multiple for loops in one line of if condition in python? (specific to DOCX)
我有以下代码。
for row in table.rows:
for cell in row.cells:
if cell.tables:
<some code>
else:
<different code>
但是我需要把它写成一行,这样 else
中的 <different code>
只会 运行 一次,而不是因为循环多次。
if any(cell.tables for cell in row.cells for row in table.rows):
<some code>
else:
<different code>
但是,这一行在 row.cells 处显示 未解决的引用 'row' 错误。这一个班轮工作,但不知道为什么它不在这个 docx table 案例中。
如果条件允许,我也愿意接受建议,如果这可以用一种不同的更好的方式来完成,而不是一个班轮。
你可以在 python.
中创建一个叫做嵌套列表函数的东西
看这个例子:
iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']
for x in iter1:
for y in iter2:
print(x, y)
print("------")
# Method 1: Nested List Comprehension
[print(x, y) for x in iter1 for y in iter2]
print("------")
# Method 2: exec()
exec("for x in iter1:\n for y in iter2:\n print(x, y)")
print("------")
# Method 3: For Loop with List Comprehension
for x in iter1: [print(x, y) for y in iter2]
所有示例重现以下输出:
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
在你的情况下你应该这样做:
您需要放置一个条件元素:
for x in iter1: [print(x, y) for y in iter2 if y=='a']
您的 for
条款被撤销了。您试图在第一个 for
子句中引用 row
,然后在第二个子句中定义它。这就是它不起作用的原因。
你是说
if any(cell.tables for row in table.rows for cell in row.cells):
...
我有以下代码。
for row in table.rows:
for cell in row.cells:
if cell.tables:
<some code>
else:
<different code>
但是我需要把它写成一行,这样 else
中的 <different code>
只会 运行 一次,而不是因为循环多次。
if any(cell.tables for cell in row.cells for row in table.rows):
<some code>
else:
<different code>
但是,这一行在 row.cells 处显示 未解决的引用 'row' 错误。这一个班轮工作,但不知道为什么它不在这个 docx table 案例中。 如果条件允许,我也愿意接受建议,如果这可以用一种不同的更好的方式来完成,而不是一个班轮。
你可以在 python.
中创建一个叫做嵌套列表函数的东西看这个例子:
iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']
for x in iter1:
for y in iter2:
print(x, y)
print("------")
# Method 1: Nested List Comprehension
[print(x, y) for x in iter1 for y in iter2]
print("------")
# Method 2: exec()
exec("for x in iter1:\n for y in iter2:\n print(x, y)")
print("------")
# Method 3: For Loop with List Comprehension
for x in iter1: [print(x, y) for y in iter2]
所有示例重现以下输出:
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
在你的情况下你应该这样做:
您需要放置一个条件元素:
for x in iter1: [print(x, y) for y in iter2 if y=='a']
您的 for
条款被撤销了。您试图在第一个 for
子句中引用 row
,然后在第二个子句中定义它。这就是它不起作用的原因。
你是说
if any(cell.tables for row in table.rows for cell in row.cells):
...