Python 过滤功能 - 单一结果

Python filter function - single result

Python 中是否有一个内置函数可以 return 给出一个列表和一个验证函数的单个结果?

例如,我知道我可以执行以下操作:

    resource = list(filter(lambda x: x.uri == uri, subject.resources))[0]

以上将根据 resource.uri 字段从资源列表中提取资源。尽管此字段值是唯一的,所以我知道我将得到 1 个或 0 个结果。 filter 函数将迭代整个列表。在我的例子中它有 20 个元素,但我想知道是否有其他内置方法可以在第一次匹配时停止迭代。

https://docs.python.org/3/library/functions.html#next

next(iterator[, default])

Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

例如在你的情况下:

resource = next(filter(lambda x: x.uri == uri, subject.resources), None)