White Science Python (21): base generator

Life is short, I chose Python

The foregoing Portal

White learn Python (1): Opening

White Science Python (2): basic data type (on)

White Science Python (3): fundamental data types (lower)

White Science Python (4): Variable Basic Operation

White Science Python (5): base operator (on)

White Science Python (6): base operator (lower)

White Science Python (7): based flow control (on)

White Science Python (8): the basis of flow control (lower)

White Science Python (9): basic data structure (list) (a)

White Science Python (10): basic data structure (list) (lower)

White Science Python (11): basic data structure (tuples)

White Science Python (12): basic data structure (dictionary) (a)

White Science Python (13): basic data structure (dictionary) (lower)

White Science Python (14): basic data structure (set) (a)

White Science Python (15): basic data structure (set) (lower)

White Science Python (16): the basic data type (function) (a)

White Science Python (17): the basic data type (function) (lower)

White learn Python (18): basic file operations

White learn Python (18): basic file operations

White learn Python (19): base Exception Handling

White learn Python (20): iterator basis

Builder

We talked earlier why you want to use iterators, you students should have the impression it (say it is not too much).

The list is too large will take up too much memory, you can use an iterator, only to come up with part of the need to use.

Design principles and iterators generator is similar to, if you need a very large collection, not all the elements in this collection, but will save the state of the element to generate each iteration when a return value.

For example, we want to generate a list of the following options are available:

list1 = [x*x for x in range(10)]
print(list1)

The results are as follows:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

If we generate a list of very large, such as:

list2 = [x*x for x in range(1000000000000000000000000)]

The results are as follows:

Traceback (most recent call last):
  File "D:/Development/Projects/python-learning/base-generator/Demo.py", line 3, in <module>
    list2 = [x*x for x in range(1000000000000000000000000)]
  File "D:/Development/Projects/python-learning/base-generator/Demo.py", line 3, in <listcomp>
    list2 = [x*x for x in range(1000000000000000000000000)]
MemoryError

Error, the error message prompts us to store abnormal, and the entire program is running for a long period of time. Friendly reminder, so please be careful to create a big list, if the computer is not configured computer will most likely stuck.

If we use the generator will be very convenient, and execution speed whizzing.

generator1 = (x*x for x in range(1000000000000000000000000))
print(generator1)
print(type(generator1))

The results are as follows:

<generator object <genexpr> at 0x0000014383E85B48>
<class 'generator'>

So, we used the generator after, how to read the data generator to generate it?

Of course, and before the iterator same pull, use the next()function:

generator2 = (x*x for x in range(3))
print(next(generator2))
print(next(generator2))
print(next(generator2))
print(next(generator2))

The results are as follows:

Traceback (most recent call last):
  File "D:/Development/Projects/python-learning/base-generator/Demo.py", line 14, in <module>
    print(next(generator2))
StopIteration

Until the end, throw StopIterationan exception.

However, use of this method, we do not know when it will end iteration, so we can use a for loop to get the specific elements of each generator to generate and use a for loop and also do not care about the last StopIterationexception.

generator3 = (x*x for x in range(5))
for index in generator3:
    print(index)

The results are as follows:

0
1
4
9
16

generatorVery powerful, in essence, generatordo not take our specific storage elements, it is estimated storage algorithm by algorithm to calculate the next value.

If the projection algorithm is complex, when a similar list with the formula for loop can not be achieved, it can also be implemented as a function.

For example, we define a function, emmmmmm, or simply point it, we understand the spirit:

def print_a(max):
    i = 0
    while i < max:
        i += 1
        yield i

a = print_a(10)
print(a)
print(type(a))

The results are as follows:

<generator object print_a at 0x00000278C6AA5CC8>
<class 'generator'>

Use the keyword here yield, yieldand returnvery similar, you can return a value, but the difference is yieldnot the end of the function.

We call this a few times with a generator function to create:

print(next(a))
print(next(a))
print(next(a))
print(next(a))

The results are as follows:

1
2
3
4

We can see that when we use the next () to builder once operated, returns the value of a cycle, in yieldthis end of this operation. But when the next execution of the next (), and will be followed by the last break point and then run. Until the next yield, and stop the cycle, until the last operation to the generator.

And there is a next () equivalent manner, the sample code to see it directly:

print(a.__next__())
print(a.__next__())

The results are as follows:

5
6

Next to introduce this method is even more powerful, not only iteration, but also a value to the function re-transmission back:

def print_b(max):
    i = 0
    while i < max:
        i += 1
        args = yield i
        print('传入参数为:' + args)

b = print_b(20)
print(next(b))
print(b.send('Python'))

The results are as follows:

1
传入参数为:Python
2

The above talked about so much, you may not think generator can have any specific role in it, and here I offer one - coroutine.

What is the introduction to the introduction before the first coroutine What is multi-threaded, that is, in the same time can execute multiple programs, simple to understand is that you usually might very often while playing cell phone while listening to music (there is no sense of violation and).

Coroutine more appropriate explanation is pipelined, something must be such as do first step A, B do step, and if the two things appear simultaneously.

def print_c():
    while True:
        print('执行 A ')
        yield None
def print_d():
    while True:
        print('执行 B ')
        yield None

c = print_c()
d = print_d()
while True:
    c.__next__()
    d.__next__()

The results are as follows:

...
执行 A 
执行 B 
执行 A 
执行 B 
执行 A 
执行 B 
执行 A 
执行 B 
执行 A 
执行 B 
...

Because the whilecondition is never really set up, so this is not going to stop the cycle.

Here we define two generators, and in a loop calling these two generators back and forth, so it looks that two tasks simultaneously executed.

Finally coroutine may be a little difficult to understand, there are questions you can ask me oh ~~~ background in public No.

Sample Code

This series of small series all the code will be placed on code management repository Github and Gitee, to facilitate access.

Sample Code -Github

Sample Code -Gitee

Guess you like

Origin www.cnblogs.com/babycomeon/p/11854666.html