简体   繁体   English

Python For Loop列表理解

[英]Python For Loop list comprehension

I am looking for a possible equivalent of the following loop in python list comprehension. 我在python列表理解中寻找以下循环的可能等效项。

    for foo in foos:
        if foo.text == expected_text
            return foo
    return []

Something like this. 这样的事情。

found_foo = [foo for foo in foos if foo.text == expected_text]

If this possible using list comprehension? 是否可以使用列表理解?

You can use generator expression and next : 您可以使用生成器表达式next

return next((foo for foo in foos if foo.text == expected_text), None)

Next will return the first yielded item that meet the condition. 下一步将返回满足条件的第一个屈服项。

In case of no matched item, next will return the default value None . 如果没有匹配项,则next将返回默认值None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM