iterator wrapper
Simon Forman
rogue_pedro at yahoo.com
Fri Aug 11 23:00:13 EDT 2006
alf wrote:
> Simon Forman wrote:
>
> >>>>>class LW(object): # ListWrapper
> >>... def __init__(self, i):
> >>... self.theiter = i
> >>... def next(self):
> >>... return [self.theiter.next()]
>
>
> I hoped one lamda would take care of it but looks like it is a simplest
> choice.
>
> > |>> I = ([n] for n in i)
>
> This is nice but I am iterating thru hude objects (like MBs) so you know ...
>
>
> Thx for responding ...
>
>
> A.
No, I don't know... :-)
My friend, I think you've misunderstood. Observe:
|>> L = [n for n in range(3)]
|>> G = (n for n in range(3))
|>> L
[0, 1, 2]
|>> G
<generator object at 0xb7d982ec>
|>> L.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'list' object has no attribute 'next'
|>> G.next()
0
List comprehensions [] create lists, generator comprehensions () create
generators.
Generator comprehensions work "just-in-time", pulling items from
whatever they're iterating over as they themselves are iterated over,
as I hope this example makes clear:
|>> i = iter(xrange(3))
|>> G = ([n] for n in i)
|>> G.next()
[0]
|>> i.next()
1
|>> G.next()
[2]
|>> G.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
So, ([n] for n in i) is indeed sufficient to your needs, as I
understand them.
BTW, the ()'s of a function call serve to create generator
comprehensions:
|>> sum(n * 2 for n in range(3))
6
Neat, eh?
HTH,
~Simon
"Some say it is better to give than to receive. We say it is better to
take than to receive. Note the subtle difference."
More information about the Python-list
mailing list