First, Generator (ITER)
From Python2.2 onwards, the generator provides a concise way to help return the function of a list element to complete simple and efficient code.
It is based on the yield instruction, allowing the STOP function and returning the result immediately.
This function saves its execution context and, if necessary, resumes execution immediately.
1, compare range and xrange difference
>>> print Range [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> print xrange (Ten) xrange (10)
As shown in the code above,range creates all the specified numbers in memory , and Xrange is not created immediately, and each array is created only during iteration loops.
def nrange (num): = 1 while True: = temp + 1 if temp >= num: return c12/>Else: yield Temp
Custom Iteration Number generator
#!/usr/bin/env python#_*_ coding:utf-8 _*_defxrange ():Print(11) yield1Print(22) yield2Print(33) yield3#just get a generator #含有yield的函数叫做生成器函数R = xrange ()#This is a generator#__next__ method for generatorsret= R.__next__()Print(ret) RET= R.__next__()Print(ret) RET= R.__next__()Print(ret)
Buy a generator in class
#!/usr/bin/env python#_*_ coding:utf-8 _*_defn2 (start,stop): Start=Start whileStop:yieldStart Start+=1defXrange2 (start,stop): obj=n2 (start,stop) forIinchRange (start,stop): J= obj.__next__() Print(j)defN1 (Stop): Start=0 whileStop:yieldStart Start+=1defXrange1 (stop): obj=N1 (stop) forIinchRange (stop): J= obj.__next__() Print(j)defXrange (*args):ifLen (args) = = 1: Xrange1 (*args)elifLen (args) = = 2: Xrange2 (*args)Else: Print("parameter is not 1 or 2")if __name__=="__main__": Xrange (2,11)
practice in Class
2. The difference between read and Xreadlinex of file operation
Read reads everything into memory Xreadlines is only available at Loop iterations
defNreadlines (): With open ('Log','R') as F: whileTrue:line=F.next ()ifLine :yield LineElse: return forIinchnreadlines ():PrintI
based on next custom generator Nreadlines
defNreadlines (): With open ('Log','R') as F:seek=0 whileTrue:f.seek (seek) data=F.readline ()ifData:seek=F.tell ()yieldDataElse: return forIteminchnreadlines ():PrintItem
Custom generator based on Seek and tell Nreadlines
second, the iterator iterators
An iterator is just a container object that implements an iterator protocol. It has two basic methods:
1) Next method
Returns the next element of the container
2) __iter__ method
Returns the iterator itself
Iterators can be created using the built-in ITER method, see example:
>>> i = ITER (' abc ') >>> I.next () ' A ' >>> i.next () ' B ' >>> i.next () ' C ' >>> I.next () Traceback (most recent): File ' <string> ', line 1, in <string>stopiteration:
Python full Stack road 8--iterator (ITER) and generator (yield)