14. Generators in Python

Using a generator, a sequence of values ​​can be generated for iteration, and the sequence of values ​​is not generated at a time, but using one and then generating another can save a lot of memory in the program.


1. Creation of the generator

A generator object is a function object defined by using the yield keyword, so a generator is also a function; a generator is used to generate a sequence for use in an iterator.

Generator example:

def myYield(n):

    while n > 0:
        print('开始生成...')
        yield n
        print('完成一次...')
        n -= 1

if __name__ == '__main__':     
    for i in myYield(4):
        print('遍历到的值:', i)
    print('-------' * 2)
    my_yield = myYield(3)
    print('第一次调用')
    print(my_yield.__next__())
    print('第二次调用')
    print(my_yield.__next__())

operation result:

开始生成...
遍历到的值: 4
完成一次...
开始生成...
遍历到的值: 3
完成一次...
开始生成...
遍历到的值: 2
完成一次...
开始生成...
遍历到的值: 1
完成一次...
--------------
第一次调用
开始生成...
3
第二次调用
完成一次...
开始生成...
2

Description: Every time my_yield.__next__() is executed, it stops after entering the function and executes yield n, and continues to execute after the next manual call;


2. Generators and Coroutines

Use the generator's send() method to reset the generator's production sequence, called a coroutine.

Coroutine example:

def myYield2(n):
    while n > 0:
        rcv = yield n
        n -= 1
        print(rcv, n)
        if rcv is not None:
            n = rcv

#if __name__ == '__main__':      
    my_yield = myYield2(3)
    print(my_yield.__next__())
    print(my_yield.__next__())
    print('传给生成器值:')
    print(my_yield.send(10))
    print('---')
    print(my_yield.__next__())

operation result:

3
None 2
2
传给生成器值:
10 1
10
---
None 9
9

Description: After calling the send() method, assign the value of rcv to 10, and continue to execute until the yield is executed and hang up; if the send() method is not used, the value of rcv is None.

If the send() method is used for the first time, None must be passed or the program will report an error.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588828&siteId=291194637