iterator wrapper

Simon Forman rogue_pedro at yahoo.com
Fri Aug 11 20:01:57 EDT 2006


John Machin wrote:
> alf wrote:
> > Hi,
> >
> > I have a following task: let's say I do have an iterator returning the
> > some objects:
> >
> >  >>i=<iterator>
> >  >>i.next()
> > 1
> >  >>i.next()
> > 'abgfdgdfg'
> >  >>i.next()
> > <some object>
> >
> >
> > For some reason I need to wrap thos objects with a list. I thought I
> > could have a smart lamda or simple function class yielding following result:
> >
> >
> >  >>i=<iterator>
> >  >>i=list_wrapper(i)
> >  >>i.next()
> > [1]
> >  >>i.next()
> > ['abgfdgdfg']
> >  >>i.next()
> > [<some object>]
> >
> >
> > What would thesolution?
> >
>
> If I understand you correctly, something like this:
>
> >>> stuff = ['a', 'b', 'c', 'd']
> >>> i1 = iter(stuff)
> >>> i1.next()
> 'a'
> >>> i1.next()
> 'b'
> >>> class LW(object): # ListWrapper
> ...     def __init__(self, i):
> ...         self.theiter = i
> ...     def next(self):
> ...         return [self.theiter.next()]
> ...
> >>> i2 = iter(stuff)
> >>> x = LW(i2)
> >>> x.next()
> ['a']
> >>> x.next()
> ['b']
> >>> x.next()
> ['c']
> >>> x.next()
> ['d']
> >>> x.next()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 5, in next
> StopIteration
>
> Cheers,
> John

You could also use a generator comprehension:

([n] for n in i)

|>> i = iter(xrange(3)) # iter() just for kicks..
|>> I = ([n] for n in i)
|>> I.next()
[0]
|>> I.next()
[1]
|>> I.next()
[2]
|>> I.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

Peace,
~Simon




More information about the Python-list mailing list