python 中的生成器(generator)

生成器不会吧结果保存在一个系列里,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到StopTteration异常结束

1、生成器语法:

  生成器表达式:通列表解析语法,只不过把列表解析的[] 换成()

  生成器表达式能做的事情列表解析基本能处理,只不过在需要的序列比较大时,列表解析比较非内存

2、生成器函数:
  在函数中出现 yield 关键字,那么该函式就不在是普通的函数,而是生成器函数

  但是生成器函数可以生产一个无限的序列,这样列表根本没有办法进行处理

  yield 的作用就是把一个函数变成一个 generator ,带有 yield 的函数不再是一个普通的函数,Python 解释器会将其视为一个 generator

3、yield 与 return

  在一个生成器中,如果没有 return ,则默认执行到函数完毕时返回 StopTterration

def gen():
    yield 'a'



>>> g = gen()
>>> next(g)
traceback (most recent call last):
    File"<stdin>", line 1, in <module>
StopIterration

  如果在执行的过程中遇到 return , 则直接抛出 StopIteration 终止迭代

def gen():
    yield 'a'
    return 
    yield 'b'

>>>g = gen()
>>>next(g)       # 程序停留在执行玩yield “a” 语句后的位置
‘a’
>>>next(g)   # 程序发现下一条语句时return,所以抛出 StopTieration,这样 yield ‘b’ 语句永远不会执行
Traceback (most recent call last):
        File"<stdin>", line 1, in <module>
StopIteraion

生成器支持的方法

1、close()

  手动关闭生成器,后面的调用会直接返回StopIteration 异常

>>>def gen():
    yield 1
    yield 2
    yield 3

>>>g = gen()
>>>next(g)
1
>>>g.close()  # 关闭后 yield 2yield 3 语句将不会在起作用
Traceback (most call last):
    File "<stdin>", line 1, in <module>
StopIteration

2、send()

  生成器函数最大的特点是可以接受外部传入一个变量,根据变量内容计算结果后返回

  这是生成器函数最难理解的地方,也是最重要的地方,携程就全靠他了

def gen():
    value=0
    while True:
        receive=yield value
        if receive=='e':
            break
        value = 'got: %s' % receive

g=gen()
print(g.send(None))     
print(g.send('aaa'))
print(g.send(3))
print(g.send('e'))

执行流程:

  1、通过g.send(None) 或者 next(g) 可以启动器函数,并执行第一个 yield 语句结束的位置

    此时,执行完了 yield 语句,但是没有给 receive 赋值, yield value 会输出初始值0

  2、通过 g.send('aaa'),会传入 aaa, 并赋值给 receive ,然后计算value的值,并回到 while 头部,执行 yield value 语句有停止

    此时 yield value 会输出 ‘’got‘ aaa, 然后挂起

  3、通过 g.send(3), 会重复第二步,最后输出结果 为 “got:”3

  4、当我们 g.send('e') 时,程序执行break然后退出循环,最后整个函数执行完毕,所以会得到 StopItration异常

0
got: aaa
got: 3
Traceback (most recent call last):
File "h.py", line 14, in <module>
  print(g.send('e'))
StopIteration

3、throw()

  用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常

  throw()后直接排除异常结束程序。或者消耗掉一个 yield,或者在没有下一个 yiled 的时候直接进行到程序的结尾

def gen():
    while True: 
        try:
            yield 'normal value'
            yield 'normal value 2'
            print('here')
        except ValueError:
            print('we got ValueError here')
        except TypeError:
            break

g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))

输出结果为:

normal value
we got ValueError here
normal value
normal value 2
Traceback (most recent call last):
  File "h.py", line 15, in <module>
    print(g.throw(TypeError))
StopIteration

执行流程:

  1、print(next(g)): 会输出 Normal value,并停留在 yield ’normal value‘之前

  2、由于执行了 g.throw(TypeError), 所以会跳过所有后续的 try 语句,也就是说 “yield ’normal value2‘” 不会被执行,让后进入到 except 语句,打印出 we got ValueError here

    然后再次进入到while循环语句部分,消耗掉一个 yield ,所以会输出 normal value

  3,print(next(g)),会执行 yield normal value2  语句,并停留在下hi行语句后的位置

  4、g.throw(TypeError):会跳出 try 语句,从而 print(’here‘) 不会执行,跳出while循环,然后到达程序结尾,所以抛出 StopIteration 异常

综合例子,把一个多维列表展开,或者说扁平化多维列表

def flatten(nested):
    
    try:
        #如果是字符串,那么手动抛出TypeError。
        if isinstance(nested, str):
            raise TypeError
        for sublist in nested:
            #yield flatten(sublist)
            for element in flatten(sublist):
                #yield element
                print('got:', element)
    except TypeError:
        #print('here')
        yield nested
        
L=['aaadf',[1,2,3],2,4,[5,[6,[8,[9]],'ddf'],7]]
for num in flatten(L):
    print(num)

  

4、yield from

  yield 产生的函数就是一个迭代器,所我们通常会把它放在循环中进行输出结果,有时候我们需要把这个 yield 产生的迭代器放在一个生成器函数中,也就是生成器嵌套。

下面例子:

def inner():
    for i in range(10):
        yield i
def outer():
    g_inner=inner()    #这是一个生成器
    while True:
        res = g_inner.send(None)
        yield res

g_outer=outer()
while True:
    try:
        print(g_outer.send(None))
    except StopIteration:
        break

这里有两篇写的很好的文章:

http://blog.theerrorlog.com/yield-from-in-python-3.html
http://stackoverflow.com/questions/9708902/in-practice-what-are-the-main-uses-for-the-new-yield-from-syntax-in-python-3

总结

  1、按照鸭子模型理论,生成器就是一种迭代器,可以使用for 循环进行迭代

  2、第一次执行 next(generator)时,会执行完yield 语句后程序进行挂起,所有的参数和状态进行保存

    再一次执行next(generator)时,会从挂起的状态开始往后执行

  在遇到程序结尾或者 StopIteration 时,循环结束

  3、可以通过 generator。send(arg) ;来传入参数,这是协程模型

  4、可以通过 generator。throw(exception)来传入一个异常,throw 语句会消耗掉一个 yield

    可以通过generator。close() 来手动关闭生成器

  5、next() 等价与send(None)

猜你喜欢

转载自www.cnblogs.com/jcjc/p/11423468.html
今日推荐