查找条件为真的第一个列表元素



我正在寻找一种优雅的(简短的!)方法来返回匹配特定条件的列表的第一个元素,而不必为列表的每个元素计算条件。最后我想到了:

(e for e in mylist if my_criteria(e)).next()

有更好的方法吗?

更准确地说:有内置的python函数,如all()any() -难道没有像first()这样的东西也有意义吗?由于某种原因,我不喜欢在我的解决方案中调用next()

如何:

next((e for e in mylist if my_criteria(e)), None)

没有-看起来很好。我可能会想重写为:

from itertools import ifilter
next(ifilter(my_criteria, e))

或者至少将计算分解到生成器中,然后使用它:

blah = (my_function(e) for e in whatever)
next(blah) # possibly use a default value

另一种方法,如果你不喜欢next:

from itertools import islice
val, = islice(blah, 1)

如果是"empty"那么ValueError就会例外

我建议使用

next((e for e in mylist if my_criteria(e)), None)

next(ifilter(my_criteria, mylist), None)

with for loop

lst = [False,'a',9,3.0]
for x in lst:
    if(isinstance(x,float)):
        res = x
        break
print res

相关内容

最新更新