查找条件为真的第一个列表元素 [英] Finding the first list element for which a condition is true

查看:45
本文介绍了查找条件为真的第一个列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种优雅的(简短的!)方法来返回匹配特定条件的列表的第一个元素,而不必评估列表中每个元素的条件.最终我想出了:

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()

有更好的方法吗?

更准确地说:有内置的 Python 函数,例如 all()any() - 使用类似 的函数难道没有意义吗?first() 也是吗?出于某种原因,我不喜欢在我的解决方案中调用 next().

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.

推荐答案

不 - 看起来不错.我很想重新写成:

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

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

Another approach, if you don't like next:

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

如果它是空的",这会给你一个 ValueError 作为异常

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

这篇关于查找条件为真的第一个列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆