Iterators and generators
Iterators
Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.
An iterator is an object that remembers where to traverse.
The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.
Iterators have two basic methods:iter () and next ().
A string, list, or tuple object can be used to create an iterator:
Two instances
List = [1,2,3,4]it = iter (list) for x in it: print (x, end= "")
Import sys list = [1,2,3,4]it = iter (list) while True: try: print (Next (IT)) except stopiteration: Sys.exit ()
Generator
In Python, a function that uses yield is called a generator (generator).
Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.
In the process of calling the generator to run, the function pauses and saves all current run information, returning the value of yield, each time the yield is encountered.
and continue running from the current location the next time the next () method is executed.
Invokes a generator function that returns an Iterator object.
In short, a yield pause is encountered, and the next call continues from the current position
Two instances
--Fibonacci Series
def Fibonacci (N): # Generator Function-Fibonacci A, b, counter = 0, 1, 0 while True: if (Counter > N): return y Ield a , B = B, a + b counter + = 1f = Fibonacci (Ten) # F is an iterator that is returned by the generator while True: try: print (Next (f ), end= "") except stopiteration: sys.exit ()
--Judging prime numbers
Import Sysimport mathdef tem (n): for T in range (2,N): for x in range (2,int (math.sqrt (t)) + 1): if t% x = = 0: Break ; else: yield tf = tem (+ 1): try: print (Next (f), end = ') except stopiteration: Sys.exi T ()
Resources
Http://www.runoob.com/python3/python3-function.html
Getting Started with Python (iii)