Builder yield and next () parses usage

Generator concepts:

python using generators to delay operations provide support, is needed only to produce results rather than produce results.

  • Generator function:

    And other functions written in the same way, using the yieldstatement once again returned results, suspends the current state between each result, the next call to proceed directly to the current state.

  • Generator expression:

    Similar to list comprehensions, except that he returns an iterator object instead of a list.

#列表生成器:
L = [x for x in range(5)]
print(L)
#简单生成器:
G= (x for x in range(5))
print(next(G))
print(next(G))
print(next(G))
print(next(G))
print(next(G))
When we output the result is a one output:
  • 1. Create an iterator class, written into the code, with the object class to create iteration, then the iteration results out with next () function.
    class test_Iterator():
        def __init__(self):
            self.a=0
            self.b=1
        def __iter__(self):
            return self
        def __next__(self):
            num = self.a
            self.a,self.b=self.b,self.b+self.a
            return num
    
    itera = test_Iterator()
    print(next(itera))
    print(next(itera))
    print(next(itera))
    print(next(itera))
    print(next(itera))
    print(next(itera))
    ########################################################
    0
    1
    1
    2
    3
    5      
  • 2. A suitable location function code plus yield, this time becomes a function of the generator
    def test():
        a = 1
        b = 2
        while True:
            yield a 
            a,b = b,a*b
    
    
    generator = test()
    
    print(next(generator))
    print(next(generator))
    print(next(generator))
    print(next(generator))
    print(next(generator))
    print(next(generator))
    print(next(generator))
    print(next(generator))
    #######################################
    1
    2
    2
    4
    8
    32
    256
    8192
    第一次用next()唤醒生成器时,从函数的开头开始运行,遇到yield a,返回a,然后暂停函数,并记住函数是运行到这个位置的。
    
    第二次唤醒生成器,从yield a断点处开始,然后a,b开始赋值,while True循环又遇见yield a,返回a,然后暂停函数,并记住函数是运行到这个位置的
  • 3. yield receiver parameter generator, send () Method:
    #b = yield,会把yield接收的值赋值给b。
    def test():
        a = 1
        while True:
            recv = yield a
            print('接收值:',recv)
    
    
    gen = test()
    
    print(next(gen))
    print(gen.send('Jhonsenry'))
    print(gen.send('a bad guy'))
    ##############################################################################
    1
    接收值: Jhonsenry
    1
    接收值: a bad guy
    1

Guess you like

Origin www.cnblogs.com/Zhao159461/p/11416490.html