Iterations are similar to loops, and each repetition is called an iterative process, and the result of each iteration is used as the initial value for the next iteration, and the container that provides the iterative method is called an iterator.
Common iterators are ( lists, Ganso, dictionaries, strings, files , etc.), usually we use the FOR statement to complete the iteration
#使用forexamples of iterative dictionaries:
>>> links = {"Fish C Studio":"http://www.fishc.com/", "Fish C Forum":"http://bbc.fishc.com"}>>> foreachinchLinks:Print("%s-->%s"%(Each,links[each])); Fish C Forum-->http://bbc.fishc.com Fish C Studio-->http://www.fishc.com/>>>
Python itself provides two BIF functions iter (), Next ()
Use the ITER () function for an object to get its iterator object
Calling the next () iterator will return the next value
ID of iteration End: Python throws a stopiteration exception.
>>> string ="123">>> it =iter (String)>>>Next (IT)'1'>>>Next (IT)'2'>>>Next (IT)'3'>>>Next (IT) Traceback (most recent): File"<pyshell#24>", Line 1,inch<module>Next (IT) stopiteration>>>
The Magic Method for ITER () is __iter__ (), and Next () corresponds to the magical method of __next__ ().
__iter__ () is actually return self, and next () determines the rules of the iterator
>>>classFibs:def __init__(self,n=10): SELF.A=0 self.b= 1SELF.N=Ndef __iter__(self):return Selfdef __next__(self): self.a,self.b= self.b,self.a+self.bifSelf.a>SELF.N:RaisestopiterationreturnSELF.A>>> fibs =Fibs ()>>> foreachinchfibs:Print(each)112358>>> fibs = fibs (100)>>> foreachinchfibs:Print(each)1123581321345589>>>
Python Learning note 010_ iterator