查找条件为true的第一个列表元素[duplicate]

时间:2020-12-08 12:58:49

This question already has an answer here:

这个问题已经有了答案:

I was looking for an elegant (short!) way to return the first element of a list that matches a certain criteria without necessarily having to evaluate the criteria for every element of the list. Eventually I came up with:

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

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

Is there a better way to do it?

有更好的方法吗?

To be more precise: There's built in python functions such as all() and any() - wouldn't it make sense to have something like first() too? For some reason I dislike the call to next() in my solution.

更准确地说:在python函数中有内置的all()和any()—拥有first()这样的函数不是很有意义吗?出于某种原因,我不喜欢在我的解决方案中调用next()。

4 个解决方案

#1


7  

Nope - looks fine. I would be tempted to re-write possibly as:

不,看起来很好。我可能会想重新写一遍:

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

Or at least break out the computation into a generator, and then use that:

或者至少把计算分解成一个生成器,然后使用它:

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

Another approach, if you don't like next:

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

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

That'll give you a ValueError as an exception if it's "empty"

它会给你一个ValueError作为一个异常如果它是"empty"

#2


8  

How about:

如何:

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

#3


1  

I propose to use

我建议使用

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

or

next(ifilter(my_criteria, mylist), None)

#4


0  

with for loop

用for循环

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

print res

#1


7  

Nope - looks fine. I would be tempted to re-write possibly as:

不,看起来很好。我可能会想重新写一遍:

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

Or at least break out the computation into a generator, and then use that:

或者至少把计算分解成一个生成器,然后使用它:

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

Another approach, if you don't like next:

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

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

That'll give you a ValueError as an exception if it's "empty"

它会给你一个ValueError作为一个异常如果它是"empty"

#2


8  

How about:

如何:

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

#3


1  

I propose to use

我建议使用

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

or

next(ifilter(my_criteria, mylist), None)

#4


0  

with for loop

用for循环

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

print res