correct usage of a generator?

Peter Otten __peter__ at web.de
Mon Nov 28 11:54:48 EST 2011


Tim wrote:

> Hi, I need to generate a list of file names that increment, like this:
> fname1
> fname2
> fname3 and so on.
> 
> I don't know how many I'll need until runtime so I figure a generator is
> called for.
> 
> def fname_gen(stem):
>     i = 0
>     while True:
>         i = i+1
>         yield '%s%d' % (stem,i)
> 
> blarg = fname_gen('blarg')
> boo = fname_gen('boo')
> 
> n = 3
> for w in range(0,n):
>     in_name = blarg.next()
>     out_name = boo.next()
> 
> 
> This works, but is it the 'normal' way to accomplish the task when you
> don't know 'n' until run-time? thanks,

As a fan of the itertools module I would spell it (untested)

from itertools import count, islice, izip

def fname_gen(stem):
    return ("%s%d" % (stem, i) for i in count(1))
# ...
for in_name, out_name in islice(izip(blarg, boo), n):
   #...

but your way is perfectly OK.




More information about the Python-list mailing list