copying generatrors
Horace Enea
hjenea at earthlink.net
Tue Jun 5 22:30:34 EDT 2007
Steve,
Hey, thanks. I'll try that.
Horace
In article <-JKdnb0ntvytmvvbnZ2dnUVZ_o_inZ2d at comcast.com>,
Steven Bethard <steven.bethard at gmail.com> wrote:
> Horace Enea wrote:
> > My example wasn't very good. Here's another try:
> >
> > def foo():
> > yield 1
> > yield 2
> > yield 3
> >
> > f = foo()
> > f.next()
> > 1
> >
> > g=copy(f) # copy the generator after an iteration
> >
> > f.next()
> > 2
> > f.next()
> > 3
> >
> > g.next()
> > 2
> >
> > I want to copy the generator's state after one or more iterations.
>
> You could use itertools.tee():
>
> >>> def foo():
> ... yield 1
> ... yield 2
> ... yield 3
> ...
> >>> import itertools
> >>> f = foo()
> >>> f.next()
> 1
> >>> f, g = itertools.tee(f)
> >>> f.next()
> 2
> >>> f.next()
> 3
> >>> g.next()
> 2
> >>> g.next()
> 3
>
> But note that if your iterators get really out of sync, you could have a
> lot of elements stored in memory.
>
> STeVe
More information about the Python-list
mailing list