What is a generator?
The builder is a function that contains a special keyword yield. When invoked, the generator function returns a generator. You can use the Send,throw,close method to enable the generator to interact with the outside world.
The generator is also an iterator , but it's not just an iterator, it has the next method and behaves exactly the same as the iterator. So the generator can also be used in the Python loop,
How does the builder use?
First look at an example:
Copy Code code as follows:
#!/usr/bin/python
#-*-Coding:utf-8-*-
def flatten (nested):
For sublist in nested:
For element in sublist:
Yield element
nested = [[1,2],[3,4],[5,6]]
For num in flatten (nested):
Print num,
The result is 1,2,3,4,5,6
Recursive generators:
Copy Code code as follows:
#!/usr/bin/python
#-*-Coding:utf-8-*-
def flatten (nested):
Try
For sublist in nested:
for element in Flatten (sublist):
Yield element
Except TypeError:
Yield nested
For num in flatten ([[[1,2,3],2,4,[5,[6],7]]):
Print num
The results are: 1 2 3 2 4 5 6 7
Let's take a look at the nature of the generator
First look at the following:
Copy Code code as follows:
#!/usr/bin/python
#-*-Coding:utf-8-*-
Def simple_generator ():
Yield 1
Print Simple_generator
DEF repeater (value):
While True:
New = (yield value)
If new is not None:value = new
R = Repeater (42)
Print R.next ()
Print r.send (' hello,world! ')
The results are:
Copy Code code as follows:
<function Simple_generator at 0x10c76f6e0>
42
hello,world!
You can see:
1 The generator is a function
2 The generator has next method
3 The generator can use the Send method to interact with the outside world.