Is this PEP-able? fwhile

Fábio Santos fabiosantosart at gmail.com
Mon Jun 24 20:19:29 EDT 2013


On 25 Jun 2013 01:08, "alex23" <wuwei23 at gmail.com> wrote:
>
> On 25/06/2013 9:35 AM, Fábio Santos wrote:
>>
>>  > I'd probably just go with a generator expression to feed the for loop:
>>  >
>>  >     for X in (i for i in ListY if conditionZ):
>>  >         ....
>>
>> That is nice but it's not lazy. If the condition or the iterables took
>> too long to compute, it would be troublesome.
>
>
> I'm not sure I follow. It's a generator expression, not a list
comprehension, so the condition will be evaluated per item iterated over in
the generator, not across all valid items in ListY at once.
>

for X in (i for i in open('largefile') if is_part_of_header(i)):

The above code would be wasting time on IO and processing. It would load
another line and calculate the condition for every line of the large file
and I just wanted to loop over the few header lines.

itertools.takewhile and fwhile/for..while actually stops the loop when the
condition is not meant, while your example keeps checking the condition
until the end of file, even though it is a generator expression.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130625/7c2ef2fe/attachment.html>


More information about the Python-list mailing list