iterator wrapper

John Machin sjmachin at lexicon.net
Fri Aug 11 19:44:39 EDT 2006


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




More information about the Python-list mailing list