Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - functional "find"?

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?

like image 742
Art Avatar asked Mar 03 '10 14:03

Art


People also ask

Is there a Find function in Python?

find() is a Python library function that is used to find the index of the first occurrence of a substring from the given string. If find() is unable to locate the substring then it returns -1 instead of throwing an exception.

How does the find () function work in Python?

Python String find() The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1.

How do I find a word in Python?

String find() in Python Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.


3 Answers

Try itertools and for example ifilter.

like image 169
gruszczy Avatar answered Oct 26 '22 22:10

gruszczy


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.

like image 20
Anurag Uniyal Avatar answered Oct 27 '22 00:10

Anurag Uniyal


You can use itertools.dropwhile to skip over the items for which the supplied function returns False, then take the first item of the rest (if any). If you need the index rather than the item, incorporate enumerate from the Recipes section of itertools docs.

To reverse truth values returned by the supplied function, use a lambda (lambda x: not pred (x), where pred is the supplied function) or a named wrapper:

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

Example:

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

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.

like image 40
Michał Marczyk Avatar answered Oct 26 '22 23:10

Michał Marczyk