Python For循环列表理解

A.J*_*.J. 0 python for-loop list-comprehension

我在python列表理解中寻找可能等效的以下循环.

    for foo in foos:
        if foo.text == expected_text
            return foo
    return []
Run Code Online (Sandbox Code Playgroud)

像这样的东西.

found_foo = [foo for foo in foos if foo.text == expected_text]
Run Code Online (Sandbox Code Playgroud)

如果这可能使用列表理解?

fal*_*tru 5

您可以使用生成器表达式next:

return next((foo for foo in foos if foo.text == expected_text), None)
Run Code Online (Sandbox Code Playgroud)

接下来将返回符合条件的第一个产生的项目.

如果没有匹配的项目,next将返回默认值None.