[Python-ideas] Add "while" clauses to generator expressions

Mathias Panzenböck grosser.meister.morti at gmx.net
Sat Jan 10 18:07:43 CET 2009


Mathias Panzenböck schrieb:
> Gerald Britton schrieb:
>> I've been using Python generators for a while now.  e.g.
>>
>> a=(i for i in range(10))
>>
>> a.next()
>> a.next()
>> ...etc.
>>
>> I also find the "if" clause handy:
>>
>> a = (i for i in range(10) if i%2==0)
>>
>> (I know that range(0,12,2) will do the same thing, but it's the idea I
>> like, especially for more complex predicates.)
>>
>> I would like to know if anyone has thought of adding a "while" clause
>> as well, like this:
>>
>> a = (i for i in range(100) while i <=50)
>>
> 
> from itertools takewhile
> a = takewhile(lambda i: i <= 50, xrange(100))

typo:
from itertools import takewhile
a = takewhile(lambda i: i <= 50, xrange(100))



More information about the Python-ideas mailing list