Python Learning note 010_ iterator

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.