One, generators and generators
1, List-generated
MyList = [I*i for I in range (3) if i>1]print (mylist) run Result: [4]
You can find that the expression for the quick list is generated, for loop range (3), and if I is greater than 1, multiply it by yourself and then output.
2, generator
Mygenerator = (i*i for I in range (3)) print (mygenerator) Run Result: <generator object <genexpr> at 0x000001fb08f18 Ba0>
You can see that this generator and the list generation are very similar. Just above is [] and the following is ().
This reminds me of the range and Xrange2 functions in Python2. Range is the output of a list, and xrange generates a generator . The generator needs to use a for loop to take a value.
The benefit of the generator is that you can save memory by not having to store values in memory at once, and then calling them when you use them.
Two, yield (for creating generators)
Yield and return are very similar, and return returns only one value, and yield can output multiple values. Yield can also be understood as a return with a memory function.
Def fun1 (): For I in range (1,5): print (i) def fun2 (): For I in range (1,5): return I def fun3 (): F or I in range (1,5):
Calling the FUN1 () function outputs the 1,2,3,4,5
Call fun2 () function output is 1 (execution to return on Exit Function)
Call FUN3 (the 0 function outputs the generator and needs to be taken out using a for loop.)
The FUN3 function and the FUN2 function are compared, the FUN2 function wisdom returns 1 and then exits the function, and yield will know that it has already output the last value the next time it enters the function, so it will return the next value. Essentially executes the next () function (Python2 version)
Description: The generator created by yield is live, and you can change it when you say it with a for loop.
Python Builds and generators