Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-functional";找到“;?_Python_Functional Programming_Lambda - Fatal编程技术网

Python-functional";找到“;?

Python-functional";找到“;?,python,functional-programming,lambda,Python,Functional Programming,Lambda,我需要一个函数,它能够遍历集合,调用一个提供的函数,将集合的元素作为参数,并在从提供的函数收到“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):

我需要一个函数,它能够遍历集合,调用一个提供的函数,将集合的元素作为参数,并在从提供的函数收到“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

因此,我想知道standart python工具集中是否有类似的东西?

您可以使用
itertools.dropwhile
跳过提供的函数返回的
False
项,然后获取其余项中的第一项(如果有)。如果您需要索引而不是项目,请从中的Recipes部分合并
enumerate

要反转所提供函数返回的真值,请使用
lambda
lambda x:not pred(x)
,其中
pred
是所提供的函数)或命名包装器:

def negate(f):
    def wrapped(x):
        return not f(x)
    return wrapped
例如:

def odd(x): return x % 2 == 1
itertools.dropwhile(negate(odd), [2,4,1]).next()
# => 1

如果找不到匹配项,将抛出
StopIteration
;将它封装在自己的函数中,以引发您选择的异常。

试试看,例如。

我认为没有任何这样的函数具有如此精确的语义,而且不管怎样,您的函数很短,足够好,您可以很容易地对其进行改进以供以后使用,所以请使用它


因为简单比复杂好。

:(我认为OP的问题本身就是答案,对于简单的迭代来说,这可能更重要。我同意Anurag,但如果使用
itertools
,我认为
ifilter
会更简单。例如:
itertools.ifilter(奇数,[2,4,1])。next()
我倾向于同意
ifilter
。此外,OP的代码片段确实很好地解决了基本问题;不过,想知道标准库中有什么东西可以帮助避免为这样的东西编写代码似乎很合理。我想说,mjv对这个问题的评论完美地总结了这里的重要教训。OP的snippet是表达需求的更直接的方式(如果只是稍微长一点的话);它很可能是规定的方式,这取决于具体情况。然而,从回答中可以得出一个非常有用的见解:
关于循环,如果有疑问,请咨询/考虑itertools