Python - 函数式“查找”?
我需要一个函数,它能够迭代集合,以集合的元素作为参数调用提供的函数,并在从提供的函数接收到“True”时返回参数或其索引。
它是这样的:
def find(f, seq, index_only=True, item_only=False):
"""Return first item in sequence where f(item) == True."""
index = 0
for item in seq:
if f(item):
if index_only:
return index
if item_only:
return item
return index, item
index+= 1
raise KeyError
所以我想知道标准Python工具集中是否有类似的东西?
I need a function, which is capable of iterating over the collection, calling a supplied function with element of the collection as a parameter and returning the parameter or it's index when received "True" from supplied function.
It is somethong like this:
def find(f, seq, index_only=True, item_only=False):
"""Return first item in sequence where f(item) == True."""
index = 0
for item in seq:
if f(item):
if index_only:
return index
if item_only:
return item
return index, item
index+= 1
raise KeyError
So I am wondering whether there's anything like that in standart python toolset?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试 itertools ,例如 ifilter。
Try itertools and for example ifilter.
我不认为有任何这样的函数具有如此精确的语义,无论如何你的函数很短,足够好,你可以轻松地改进它以供以后使用,所以使用它。
因为简单总比复杂好。
I don't think there is any such function with such exact semantics, and anyway your function is short , good enough and you can easily improve it for later use, so use it.
because simple is better than complex.
您可以使用 itertools.dropwhile 跳过所提供的函数返回 False 的项目,然后获取其余项目中的第一项(如果有)。如果您需要索引而不是项目,请合并
itertools
文档。要反转提供的函数返回的真值,请使用
lambda
(lambda x: not pred (x)
,其中pred
是提供的函数) 或命名包装器:示例:
如果未找到匹配项,则会抛出
StopIteration
;将其包装在您自己的函数中以抛出您选择的异常。You can use
itertools.dropwhile
to skip over the items for which the supplied function returnsFalse
, then take the first item of the rest (if any). If you need the index rather than the item, incorporateenumerate
from the Recipes section ofitertools
docs.To reverse truth values returned by the supplied function, use a
lambda
(lambda x: not pred (x)
, wherepred
is the supplied function) or a named wrapper:Example:
This will throw
StopIteration
if no matching item is found; wrap it in a function of your own to throw an exception of your choice instead.