[pyar] Cómo obtenes N elemento de un generador?

Ale peralta.alejandro en gmail.com
Lun Ago 23 17:43:18 ART 2010


2010/8/23 Juanjo Conti <jjconti en gmail.com>

> Les dejo mi intento infructífero; cómo se hace?
>
> >>> def a():
> ...     for x in range(10):
> ...             yield x
> ...
> >>> a()
> <generator object a at 0xb76c89b4>
> >>> c = a()
> >>> c[0:4]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'generator' object is unsubscriptable
> >>> c.next()
> 0
> >>> c.next()
> 1
> >>> c.next()
> 2
>
>
hay varias formas:

1. simpre podes utilizar un while

idx = 0
elementos = []
while idx < N
    elementos.append(c.next())


2. utilizar zip (o izip)
In [2]: from itertools import count

In [3]: zip(range(4), count())
Out[3]: [(0, 0), (1, 1), (2, 2), (3, 3)]

In [4]: from itertools import izip

In [5]: izip(xrange(4), count())
Out[5]: <itertools.izip object at 0x95b0e6c>

In [6]: list(izip(xrange(4), count()))
Out[6]: [(0, 0), (1, 1), (2, 2), (3, 3)]


el problema de hacer list(generador()) es que si el generador no termina
clavas tu computadora.

capaz hay más no se me ocurren ahora

-- 
Ale.
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://listas.python.org.ar/pipermail/pyar/attachments/20100823/d15d6a13/attachment.html>


More information about the pyar mailing list