简体   繁体   English

从过滤器返回第一个元素或无

[英]Return the first element or None from filter

Is there a convenient way to return the first element or None from filter ? 是否有一种方便的方法从filter返回第一个元素或None

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] ? 而不是必须先调用list()然后再调用[0]

My question is about the method filter and not list comprehension. 我的问题是关于方法filter而不是列表理解。

filter objects are essentially iterators. filter对象本质上是迭代器。 Just use the next function to get the first value: 只需使用next函数即可获取第一个值:

next(filter(lambda x: x == 35, [3, 5, 5, 8]), None)

next(it, None) will return None if next(it) raises StopIteration . 如果next(it)引发StopIteration next(it, None)将返回None

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

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