Python Foundation------Build an iterative object with the generator

Source: Internet
Author: User
Tags iterable

#利用生成器生成一个可迭代对象
#需求: Generates an iterative object, outputs a prime number within a specified range, and uses the generator to produce an iterative object
#生成器: It is iterative in itself, but yield is like return, yield returns, function freezes state when re-tuned, starting from frozen state
1 classPrintnumbers (object):2     """docstring for Printnumbers"""3     def __init__(self, start,end):4Self.start =Start5Self.end =End6     defIsprimenum (self,num):7         ifnum==2:8             returnFalse9          forIinchRange (2, num):Ten             ifnum%i = =0: One                 returnFalse A         returnTrue -     def __iter__(self): -          forIinchRange (self.start,self.end+1): the             ifSelf.isprimenum (i): -                 yieldI -  -p = printnumbers (1,100) +  forIinchP: -     Print(i)
Slicing an iterator, similar to a list, returns the type of iteration that is still possible
1 Print("-------------slicing an iterator------------")2 #How to slice an iterator3  fromItertoolsImportIslice4 #The return is still an iterator that needs to be iterated5 " "6 islice (iterable,stop)7 islice (Iterable,start,stop[,step=1]), Islice object8 9 Ten " " OneA = Islice (p,1,3) A Print(a) -  forXinchA:

Python Foundation------Build an iterative object with the generator

Related Article

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.