简体   繁体   中英

Python For Loop list comprehension

I am looking for a possible equivalent of the following loop in python list comprehension.

    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 :

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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