is there such a built-in funciton, similar to filter
Terry Reedy
tjreedy at udel.edu
Sun Mar 5 13:46:02 EST 2006
"Michael Hoffman" <cam.ac.uk at mh391.invalid> wrote in message
news:dueg7q$o4p$1 at gemini.csx.cam.ac.uk...
> wcc wrote:
>
>> Beginner learning Python here. I know filter(lambda x: x > 3, [1, 2,
>> 5, -3, 4, 8]) will give me a list [5, 4, 8]. What if I only need to
>> find the first item in the list that returns Ture when applying the
>> filter function. In this case, I only want to get the 5, and its index
You have made two important changes to the function return value.
Filter returns a list of items. You want an item and index.
What if there is no first item?
>> 2. Is there a built-in function, or function from a module for that?
>> I think it is not hard to write a function for this. But knowing
>> Python is "battery included", I thought I'd like to ask.
A 'battery' is something like the email, html, xml modules that assist
major application areas. Not every easily written 3-line function ;-)
> You can use a generator expression like this:
>
> >>> items = [1, 2, 5, -3, 4, 8]
> >>> ((index, item) for index, item in enumerate(items) if item >
> >>> 3).next()
> (2, 5)
>>> items = [0,1,2,3]
>>> ((index, item) for index, item in enumerate(items) if item > 3).next()
Traceback (most recent call last):
File "<pyshell#82>", line 1, in -toplevel-
((index, item) for index, item in enumerate(items) if item > 3).next()
StopIteration
I believe ifilter from the itertools module will act the same.
Terry Jan Reedy
More information about the Python-list
mailing list