1. Understanding Generators
Using iterators, we can generate the data in each iteration (through the next () method) and follow a specific pattern. But when we implement an iterator, we need to record the current iteration to the state we want to generate the next data based on the current state. To achieve a record of the current state and iterate with the next () function, we can use a simpler syntax, the generator (generator). a generator is a special kind of iterator .
2. How to create a generator:
Generator is a special kind of iterator, since we know how to create an iterator, then it is not difficult to create a generator, first we first understand the first type of generator creation method:
Create a generator using the method of generator derivation
# The first generator creation Method my_list = (x for x in range) print (my_list) print (Next (my_list)) print (Next (my_list)) print (my_list) )
Execution results
012
How is it so easy to create a generator in such a way? It is important to note that the list derivation is [] and the generator derivation is (), this is not a mistake.
3. Using the generator to write Fibonacci sequences
We already know how to create a generator, and then we'll create a Fibonacci sequence by creating a second method of the generator.
First we first understand the Fibonacci sequence, the Fibonacci sequence defines the first number as 0, the second is 1, and then each number is the sum of the first two numbers, which is simply similar to the 0,1,1,2,3,5 .... The sequence
# The second way to create the generator def dome (num): a = 0 b = 1 # defines subscript value Iter_index = 0 while iter_index < num: item = A A, B = B, a + b iter_index+=1 # Returns a custom value, yield xxx is equivalent to a pause jian, next time from here the next line to start execution, and return there is a big difference send_ Values = Yield Item print (send_values) test = Dome (5) values = Next (test) print (values), values = Next (test) print ( Values
Python three great artifacts = = = Generator