Python (generator)

Builder

Start talking about the list of formula

 

 By a simple formula to generate a regular list

If [] replaced () What will happen then?

 

X no longer see the existence of a list, but an address, and this address is the address of our generator object

This is something what use is it? Of course, the friends save memory

Suppose there is a very large set of data to be processed, it seems impossible to put into memory and then processed a one-time, this time to reflect the benefits of the generator, because it only takes a data memory space, when you need to access next

Data, current data will be overwritten, so it does not matter how much data it can all be handled. The data can be accessed via a next () or __next __ ().

Of course, still have to be accessed to aid circulation elements, 100w data can not knock one million next () it.

 

 

Of course, how do these data can not be used if the expression means? The answer is to use a function key + yield, there is a function of the yield keyword is a generator.

To a chestnut (print Fibonacci number):

 

yield a return can be understood as a a, but note the current position of the code, the next time will yield under a sentence start executing code. Take this code, the talk from the last cycle.

1.next () method to start the generator, the generator to perform a

2. The program goes wile cycle

3. encountered yield a return value, and a few breakpoints

4.for cycle by the value of a print statement print a = 1

5.for continue to cycle, there is a call to next () method, the generator starts again

6. Generator find the last position code execution breakpoint (a, b = b, a + b) ...

7. encounter yield statement again, go back to step 3

......

In addition to next () method, send () generator can be started, it can send to the generator by value, and this value will replace the last breakpoint force at the return value

 

See replace send incoming parameter is the value of res, not the value of a! ! ! As for why print 'None' in fact pass a default next None so a call to next () will print None, and send the call

Print sned incoming parameters.

Finally, to a classic bar producers and consumers

 

 1 import time
 2 def consumer(name):
 3     print("%s is ready to consume" % name)
 4     while True:
 5         res = yield
 6         print("%s has consumed goods %d" % (name,res))
 7 def producer(name):
 8     print("%s is ready to produce" % name)
 9     while True:
10         time.sleep(3)
11         succ = yield 
12         print("produce goods %d and goods %d successfully" % (succ,succ+1))
13 c1 = consumer('c1')
14 c2 = consumer('c2')
15 c1.__next__()
16 c2.__next__()
17 p1 = producer('p1')
18 p1.__next__()
19 for i in range(10):
20     p1.send(i+1)
21     c1.send(i+1)
22     c2.send(i+2)

Guess you like

Origin www.cnblogs.com/planBinary/p/11746759.html