#利用生成器生成一个可迭代对象
#需求: 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