Come posso costruire una matrice numpy da un oggetto generatore?
Vorrei illustrare il problema:
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In questo caso, gimme()è il generatore il cui output mi piacerebbe trasformare in un array. Tuttavia, il costruttore dell'array non esegue l'iterazione sul generatore, ma memorizza semplicemente il generatore stesso. Il comportamento che desidero è quello di numpy.array(list(gimme())), ma non voglio pagare l'overhead di memoria di avere contemporaneamente l'elenco intermedio e l'array finale. Esiste un modo più efficiente in termini di spazio?
numpynon può (o non vuole) trattare i generatori come fa Python, almeno dovrebbe sollevare un'eccezione quando riceve un generatore come argomento.
from numpy import *; print any(False for i in range(1))- che ombreggia il built-inany()e produce il risultato opposto (come so ora).