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

Claudio Freire klaussfreire en gmail.com
Lun Ago 23 17:58:28 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
>


O sea islice?

>>> gen = xrange(1000000)
>>> import itertools
>>> slice = itertools.islice(gen,100000,200000)
>>> slice
<itertools.islice object at 0x7fe998d880a8>
>>> l = list(slice)
>>> l[:10]
[100000, 100001, 100002, 100003, 100004, 100005, 100006, 100007, 100008,
100009]
>>>
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://listas.python.org.ar/pipermail/pyar/attachments/20100823/455d4fa8/attachment.html>


More information about the pyar mailing list