Is there a more elegant way to spell this?
Jussi Piitulainen
jpiitula at ling.helsinki.fi
Tue Jan 27 09:47:34 EST 2015
Neal Becker writes:
> Jussi Piitulainen wrote:
> > Neal Becker writes:
> >
> >> Is there a more elegant way to spell this?
> >>
> >> for x in [_ for _ in seq if some_predicate]:
> >
> > If you mean some_predicate(_), then possibly this.
> >
> > for x in filter(some_predicate, seq):
> > handle(x)
> >
>
> I like this best, except probably even better:
>
> for x in ifilter (some_predicate, seq):
That's in Python 2 and in itertools, I think. In Python 3, filter is a
built-in and returns a filter object.
>>> f = filter(None, map(int, '102030'))
>>> f
<filter object at 0x217d9d0>
>>> next(f)
1
>>> list(f)
[2, 3]
>>> list(f)
[]
>>>
More information about the Python-list
mailing list