altering an object as you iterate over it?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri May 19 23:00:54 EDT 2006


bruno at modulix a écrit :
(snip)

(responding to myself)
(but under another identity - now that's a bit schizophrenic, isn't it ?-)

> For the general case, the best way to go would probably be an iterator:
> 
> def iterfilter(fileObj):
>   for line in fileObj:
>     if line.strip():
>       yield line
> 
 >
> f = open(path, 'r')
> for line in iterfilter(f):
>   doSomethingWith(line)

Which is good as an example of simple iterator, but pretty useless since 
we have itertools :

import itertools
f = open(path, 'r')
for line in itertools.ifilter(lambda l: l.strip(), f):
    doSomethingWith(line)
f.close()



More information about the Python-list mailing list