Is there a convenient way to return the first element or None
from filter
?
filter(lambda x: x == 5, [3, 5, 5, 8]) # ?? 5
filter(lambda x: x == 35, [3, 5, 5, 8]) # ?? None
instead of having to call list()
and then [0]
?
My question is about the method filter
and not list comprehension.
filter
objects are essentially iterators. Just use the next
function to get the first value:
next(filter(lambda x: x == 35, [3, 5, 5, 8]), None)
next(it, None)
will return None
if next(it)
raises StopIteration
.
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.