Objective
To understand what yield is, first understand what the generator () generator
is, say the iterator () before you speak the generator, and iterator
when you create a list (), list
you can read each item individually, which is called an iteration ( iteration
).
>>> mylist = [1, 2, 3]
>>> for i in MyList:
... print (i)
1
2
3
mylist
is an object that can be iterated. When you use a list generation to create a list, you create an iterative object:
>>> mylist = [x*x for x in range (3)]
>>> for i in MyList:
... print (i)
0
1
4
You can use " for··· in ···
" to manipulate an iterative object, such as:,,,, list
string
files
These iterative objects are very convenient for us to use, because you can do as you want to repeat the read. But you have to store all the elements in memory, when there are many elements in those objects, not every item is useful to you.
The generator is also an iterative object, but you can only read it once, because it does not hold all values in memory, and it dynamically generates values:
>>> Mygenerator = (x*x for x "range (3))
>>> for I in Mygenerator:
... print (i)
0
1
4
It seems that there is no difference except to replace [] with (). However, you cannot use it again for i in mygenerator
, because the generator can only be iterated once: first compute 0, then proceed to compute 1, then compute 4, one with ...
yield
is a similar return
keyword, except that the function returns a generator.
>>> def creategenerator ():
... mylist = range (3) ... for
i in MyList:
... Yield i*i ...
>>> mygenerator = CreateGenerator () # Create a generator
>>> print (mygenerator) # mygenerator is object!
<generator Object CreateGenerator at 0xb7555c34>
>>> to I in Mygenerator:
... Print (i)
0
1
4
The example itself makes little sense, but it's clear that the function returns a set of values that can be read only once. To master yield, the first thing to understand is that when you call a generator function, as in the example above createGenerator()
, the program does not execute code in the body of the function, it simply returns the generator object, This approach is rather subtle. The code in the function body runs only until each loop iteration (for) generator is run.
Your function will execute in the first iteration, the keyword is reached from the beginning and the yield
yield
value returned as the return value for the first iteration. Then, each execution of this function will continue to perform the next time you define the loop within the function, and then return that value until there is nothing to return.
If no keyword is defined inside the generator yield
, the generator is considered empty. This may not be the case because of the cycle, or the if/else condition is not met.
Summarize
The above is the entire content of this article, I hope this article content for you to learn or use Python can help, if you have questions you can message exchange.