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?
You can use
itertools.dropwhileto 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, incorporateenumeratefrom the Recipes section ofitertoolsdocs.To reverse truth values returned by the supplied function, use a
lambda(lambda x: not pred (x), wherepredis the supplied function) or a named wrapper:Example:
This will throw
StopIterationif no matching item is found; wrap it in a function of your own to throw an exception of your choice instead.