在1中组2嵌套循环/迭代器的干净方法?

2024-04-27 15:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有两个连续的嵌套循环,如下所示:

for p in doc.paragraphs:
    for r in p.runs:
        s = do_something(r)
        if something_else(s, r):
           r.text = another_function(s)

for table in doc.tables:
    for col in table.columns:
        for cell in col.cells:
            for p in cell.paragraphs:
                for r in p.runs:
                    s = do_something(r)
                    if something_else(s, r):
                        r.text = another_function(s)

有没有一种方法可以在不创建新函数的情况下将它们分组到一个循环中?(在大多数情况下,创建一个专用函数,并在每个嵌套循环中调用它以避免代码重复是最好的,但在这里我想探索其他方法)

我找到的唯一解决方案是:

for r in [run for p in doc.paragraphs for run in p.runs] + \
           [run for table in doc.tables for col in table.columns for cell in col.cells for p in cell.paragraphs for run in p.runs]:
    s = do_something(r)
    if something_else(s, r):
        r.text = another_function(s)

是否有更干净的方法将2个迭代器分组在一起?