Quando uso un generatore in un ciclo for, sembra "sapere", quando non ci sono più elementi restituiti. Ora, devo usare un generatore SENZA un ciclo for, e usare il prossimo() a mano, per ottenere l'elemento successivo. Il mio problema è, come faccio a sapere se non ci sono più elementi?Python 3.x: verifica se il generatore ha elementi rimanenti
I so only: successivo() genera un'eccezione (StopIteration), se non è rimasto nulla, MA non è un'eccezione un po 'troppo "pesante" per un problema così semplice? Non c'è un metodo come has_next() o così?
Le seguenti linee dovrebbero rendere chiaro, quello che voglio dire:
#!/usr/bin/python3
# define a list of some objects
bar = ['abc', 123, None, True, 456.789]
# our primitive generator
def foo(bar):
for b in bar:
yield b
# iterate, using the generator above
print('--- TEST A (for loop) ---')
for baz in foo(bar):
print(baz)
print()
# assign a new iterator to a variable
foobar = foo(bar)
print('--- TEST B (try-except) ---')
while True:
try:
print(foobar.__next__())
except StopIteration:
break
print()
# assign a new iterator to a variable
foobar = foo(bar)
# display generator members
print('--- GENERATOR MEMBERS ---')
print(', '.join(dir(foobar)))
L'uscita è la seguente:
--- TEST A (for loop) ---
abc
123
None
True
456.789
--- TEST B (try-except) ---
abc
123
None
True
456.789
--- GENERATOR MEMBERS ---
__class__, __delattr__, __doc__, __eq__, __format__, __ge__, __getattribute__, __gt__, __hash__, __init__, __iter__, __le__, __lt__, __name__, __ne__, __new__, __next__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, close, gi_code, gi_frame, gi_running, send, throw
Grazie a tutti, e buona giornata! :)
Ho appena realizzato che voglio fare 'dis' per studiare' numpy'. ;) – n611x007