[Python-Dev] Re: Reiterability

Raymond Hettinger python at rcn.com
Sun Oct 19 12:50:24 EDT 2003


> > A better name would be clone(); copy() would work too, as long as
it's
> > clear that it copies the iterator, not the underlying sequence or
> > series. (Subtle difference!)
> >
> > Reiteration is a special case of cloning: simply stash away a clone
> > before you begin. 

So far, all of my needs for re-iteration have been met by storing some
of the iterator's data. If all of it needs to be saved, I use list(it).
If only a portion needs to be saved, then I use the code from the tee() 
example in the itertools documentation:
 def tee(iterable):
 "Return two independent iterators from a single iterable"
 def gen(next, data={}, cnt=[0]):
 dpop = data.pop
 for i in itertools.count():
 if i == cnt[0]:
 item = data[i] = next()
 cnt[0] += 1
 else:
 item = dpop(i)
 yield item
 next = iter(iterable).next
 return (gen(next), gen(next))
Raymond Hettinger


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /