查找序列中与谓词匹配的第一个元素 [英] Find first element in a sequence that matches a predicate

查看:54
本文介绍了查找序列中与谓词匹配的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一种惯用的方法来查找列表中与谓词匹配的第一个元素.

I want an idiomatic way to find the first element in a list that matches a predicate.

目前的代码很丑:

[x for x in seq if predicate(x)][0]

我已经考虑将其更改为:

I've thought about changing it to:

from itertools import dropwhile
dropwhile(lambda x: not predicate(x), seq).next()

但必须有更优雅的东西......如果它返回一个 None 值,而不是在没有找到匹配的情况下引发异常,那就太好了.

But there must be something more elegant... And it would be nice if it returns a None value rather than raise an exception if no match is found.

我知道我可以定义一个函数,例如:

I know I could just define a function like:

def get_first(predicate, seq):
    for i in seq:
        if predicate(i): return i
    return None

但是用这样的实用函数开始填充代码是很无味的(人们可能不会注意到它们已经存在,所以随着时间的推移它们往往会重复)如果已经提供了相同的内置函数.

But it is quite tasteless to start filling the code with utility functions like this (and people will probably not notice that they are already there, so they tend to be repeated over time) if there are built ins that already provide the same.

推荐答案

在序列 seq 中找到与 predicate 匹配的第一个元素:

To find the first element in a sequence seq that matches a predicate:

next(x for x in seq if predicate(x))

或者干脆:

Python 2:

next(itertools.ifilter(predicate, seq))

Python 3:

next(filter(predicate, seq))

如果谓词与任何元素都不匹配,这些将引发 StopIteration 异常.

These will raise a StopIteration exception if the predicate does not match for any element.

如果没有这样的元素,则返回None:

To return None if there is no such element:

next((x for x in seq if predicate(x)), None)

或者:

next(filter(predicate, seq), None)

这篇关于查找序列中与谓词匹配的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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