Skip to main content
 首页 » 编程设计

python之在 python 中循环遍历资源

2025年05月04日18qq号

是否有更短的方法来执行以下 for-with 组合:

for resource in gen_resources(): 
    with resource: 
        DoWork1(resource) 
        . 
        . 
        DoWorkN(resource) 

如果可能,我想避免额外的行和缩进。

资源可以是在离开循环迭代时必须完成的任何东西(打开文件、事件对象等)

请您参考如下方法:

您可以创建一个生成器函数,对每个元素执行 with 语句:

def iterate_with(iterable): 
    for element in iterable: 
        with element: 
            yield element 

使用:

for resource in iterate_with(gen_resources()): 
    DoWork(resource) 

我可能仍会在此之上使用您的原始代码,因为代码的读者可能不清楚此处使用了 with 语句。