Iterators
A dictionary of iterator sequences (list tuple strings) that we typically contact
You typically use the For statement to iterate
Python offers two bif
ITER ()
__ITER__ ()
Next ()
__next__ ()
for inch ' Junjie ' :... Print (i) ... Junjie
for inch Links: ... Print (StackOverflow,%s, '%s' )
>>> string ='Junjie'>>> it =iter (String)>>>Next (IT)'J'>>>Next (IT)'u'>>>Next (IT)'N'>>>Next (IT)'J'>>>Next (IT)'I'>>>Next (IT)'e'>>>Next (IT) Traceback (most recent): File"<stdin>", Line 1,inch<module>stopiteration
>>> string = " junjie " >>> it = iter (string) >>> while True: ... try : ... each = next (it) ... except stopiteration: ... break ... print
for inch string: ... Print (each) ... Junjie
Magic method
>>>classFibs: ...def __init__(self): ... self.a=0 ... self.b= 1... def __iter__(self): ...returnSelf ...def __next__(self): ... self.a,self.b= self.b,self.a+self.b ...returnself.a ...>>> foreachinchfibs: ...ifEach < 20:... Print(each) ...Else:... Break... 11235813
>>>classFibs: ...def __init__(self,n=10): ... self.a=0 ... self.b= 1. .. self.n=n . ...def __iter__(self): ...returnSelf ...def __next__(self): ... self.a,self.b= SELF.B,SELF.A +self.b ...ifSELF.A >SELF.N: ...Raisestopiteration ...returnself.a ...>>> fibs =Fibs ()>>> foreachinchfibs: ...Print(each) ...112358
Python--30 iterators