?
Paul Hankin
paul.hankin at gmail.com
Sat May 17 06:29:16 EDT 2008
On May 17, 11:08 am, Ruediger <larud... at freenet.de> wrote:
> urikaluzhny wrote:
> > It seems that I rather frequently need a list or iterator of the form
> > [x for x in <> while <>]
> > And there is no one like this.
> > May be there is another short way to write it (not as a loop). Is
> > there?
> > Thanks
>
> I usually have the same problem and i came up with an solution like that:
>
> from operator import ne
> def test(iterable, value, op=ne):
> _n = iter(iterable).next
> while True:
> _x = _n()
> if op(_x, value):
> yield _x
> else:
> raise StopIteration
This is better written using takewhile...
itertools.takewhile(lambda x: x != value, iterable)
But if you really need to reinvent the wheel, perhaps this is simpler?
def test(iterable, value, op=operator.ne):
for x in iterable:
if not op(x, value):
return
yield x
--
Paul Hankin
More information about the Python-list
mailing list