while expression feature proposal

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Oct 25 03:21:38 EDT 2012


Am 25.10.2012 01:39 schrieb Ian Kelly:
> On Wed, Oct 24, 2012 at 5:08 PM, Paul Rubin <no.email at nospam.invalid> wrote:
>> from itertools import dropwhile
>>
>> j = dropwhile(lambda j: j in selected,
>>                   iter(lambda: int(random() * n), object()))
>>               .next()
>>
>> kind of ugly, makes me wish for a few more itertools primitives, but I
>> think it expresses reasonably directly what you are trying to do.
>
> Nice, although a bit opaque.  I think I prefer it as a generator expression:
>
> j = next(j for j in iter(partial(randrange, n), None) if j not in selected)

This generator never ends. If it meets a non-matching value, it just 
skips it and goes on.

The dropwhile expression, however, stops as soon as the value is found.

I think

# iterate ad inf., because partial never returns None:
i1 = iter(partial(randrange, n), None)
# take the next value, make it None for breaking:
i2 = (j if j in selected else None for j in i1)
# and now, break on None:
i3 = iter(lambda: next(i2), None)

would do the job.


Thomas



More information about the Python-list mailing list