Python--30 iterators

Source: Internet
Author: User

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

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.