Ho queste due implementazioni per calcolare la lunghezza di un generatore finita, mantenendo i dati per ulteriori elaborazioni:Lunghezza di un generatore finita
def count_generator1(generator):
'''- build a list with the generator data
- get the length of the data
- return both the length and the original data (in a list)
WARNING: the memory use is unbounded, and infinite generators will block this'''
l = list(generator)
return len(l), l
def count_generator2(generator):
'''- get two generators from the original generator
- get the length of the data from one of them
- return both the length and the original data, as returned by tee
WARNING: tee can use up an unbounded amount of memory, and infinite generators will block this'''
for_length, saved = itertools.tee(generator, 2)
return sum(1 for _ in for_length), saved
Entrambi hanno inconvenienti, sia fare il lavoro. Qualcuno potrebbe commentarli o addirittura offrire un'alternativa migliore?
Non c'è modo di conoscere la lunghezza di un generatore iterabile senza consumare l'intera cosa. –
Lo so. Questa non è la domanda – dangonfast
nota: se se non hai bisogno della lunghezza precisa, puoi usare ['operator.length_hint()' (Python 3.4+)] (http://docs.python.org/dev/library /operator#operator.length_hint) che restituisce una lunghezza stimata senza consumare l'iteratore. Vedi [PEP 424 - Un metodo per esporre un suggerimento sulla lunghezza] (http://www.python.org/dev/peps/pep-0424/) – jfs