Art*_*Art 6 python lambda functional-programming
我需要一个函数,它能够遍历集合,调用带有集合元素的提供函数作为参数,并在从提供的函数接收到"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
Run Code Online (Sandbox Code Playgroud)
所以我想知道在标准的python工具集中是否有类似的东西?
您可以使用itertools.dropwhile跳过所提供的函数返回的项目False,然后获取其余项目的第一项(如果有)。如果您需要索引而不是项目,请从文档enumerate的食谱部分合并。itertools
要反转所提供的函数返回的真值,请使用 ( lambda,lambda x: not pred (x)其中pred是所提供的函数) 或命名包装器:
def negate(f):
def wrapped(x):
return not f(x)
return wrapped
Run Code Online (Sandbox Code Playgroud)
例子:
def odd(x): return x % 2 == 1
itertools.dropwhile(negate(odd), [2,4,1]).next()
# => 1
Run Code Online (Sandbox Code Playgroud)
StopIteration如果没有找到匹配的项目,则会抛出此异常;将其包装在您自己的函数中以抛出您选择的异常。