• Python 生成器


    生成器(generator)

    生成器不会把结果保存在一个序列中,而是保存成生成器的状态,在每次迭代时返回一个值,直到遇到StopIteration异常结束,其最大特点是用某种算法实现的一边循环一边计算的机制

    生成器语法
    1.生成器表达式:通过列表解析语法,只不过把列表解析的[]换成();生成器表达式能做的事情列表解析基本都能处理,但是在需要处理的序列比较大时,列表解析比较耗费内存空间;

    >>> gen = (x**2 for x in range(5))
    >>> gen
    <generator object <genexpr> at 0x0000000002FB7B40>
    >>> for g in gen:
    ...   print(g, end='-')
    ...
    0-1-4-9-16-
    >>> for x in [0,1,2,3,4,5]:
    ...   print(x, end='-')
    ...
    0-1-2-3-4-5-
    

    2.生成器函数:在函数中如果出现了yield关键字,那么该函数就不是普通的函数,而是生成器函数。但是生成器函数可以生产一个无限的序列,这样列表根本没有办法进行处理。yield的作用就是把一个函数编程generator,带有yield的函数不再是一个普通函数,python解释器会将其视为生成器。
    下面是一个可以产生无穷奇数的生成器函数:

    def odd():
        n = 1
        while True:
            yield n
            n += 2
    
    
    odd_num = odd()
    count = 0
    for o in odd_num:
        if count >= 5:
            break
        print(o)
        count += 1
    

    当然通过手动编写迭代器可以实现类似的效果,只不过生成器更加直观易懂。

    class Iter:
        def __init__(self):
            self.start = -1
    
        def __iter__(self):
            return self
    
        def __next__(self):
            self.start += 2
            return self.start
    
    
    i = Iter()
    for count in range(5):
        print(next(i))
    

    注意:生成器是含有__iter__()和__next__()方法的,所以可以直接使用for来迭代,而没有包含StopIteration的自编Iter只能通过手动循环来迭代。

    >>> from collections import Iterable
    >>> from collections import Iterator
    >>> isinstance(odd_num, Iterable)
    True
    >>> isinstance(odd_num, Iterator)
    True
    >>> iter(odd_num) is odd_num
    True
    >>> help(odd_num)
    Help on generator object:
    
    odd = class generator(object)
     |  Methods defined here:
     |
     |  __iter__(self, /)
     |      Implement iter(self).
     |
     |  __next__(self, /)
     |      Implement next(self).
     ......
    

    看到上面的结果,现在我们可以很有信心的按照Iterator的方式进行循环了。在for循环执行时,每次循环都会执行odd函数内部的代码,执行到yield时,odd函数就返回一个迭代值,下次迭代时,代码从yield b的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的。于是函数继续执行,直到再次遇到yield,看起来就好像一个函数在正常的执行过程中被yield中断了N次,每次中断都会通过yield返回当前的迭代值。

    yield与return
    在一个生成器种,如果没有return,则默认执行到函数完毕时返回StopIteration;

    >>> def g1():
    ...     yield 1
    ...
    >>> g=g1()
    >>> next(g)    #第一次调用next(g)时,会在执行完yield语句后挂起,所以此时程序并没有执行结束。
    1
    >>> next(g)    #程序试图从yield语句的下一条语句开始执行,发现已经到了结尾,所以抛出StopIteration异常。
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    >>>
    

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

    >>> def g2():
    ...     yield 'a'
    ...     return
    ...     yield 'b'
    ...
    >>> g=g2()
    >>> next(g)    #程序停留在执行完yield 'a'语句后的位置。
    'a'
    >>> next(g)    #程序发现下一条语句是return,所以抛出StopIteration异常,这样yield 'b'语句永远也不会执行。
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    

    如果在return返回一个值,那么这个值为StopIteration异常的说明,不是程序的返回值。

    >>> def g3():
    ...     yield 'hello'
    ...     return 'world'
    ...
    >>> g=g3()
    >>> next(g)
    'hello'
    >>> next(g)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration: world 
    

    生成器支持的方法

    >>> help(odd_num)
    Help on generator object:
    
    odd = class generator(object)
     |  Methods defined here:
     ......
     |  close(...)
     |      close() -> raise GeneratorExit inside generator.
     |
     |  send(...)
     |      send(arg) -> send 'arg' into generator,
     |      return next yielded value or raise StopIteration.
     |
     |  throw(...)
     |      throw(typ[,val[,tb]]) -> raise exception in generator,
     |      return next yielded value or raise StopIteration.
     ......
    

    close()
    手动关闭生成器函数,后面的调用会直接返回StopIteration异常。

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

    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"))
    

    以上代码执行结果为:

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

    执行流程
    1.通过g.send(None)或者next(g)可以启动生成器函数,并执行第一个yield语句结束的位置;此时,执行完了yield语句,但是没有给receive赋值,yield value会输出初始值0;注意:在启动生成器函数时,只能send(None),如果试图输入其它的值都会得到错误提示信息
    2.通过g.send("aaa"),会传入aaa,并赋值给receive,然后计算出value的值,并回到while头部,执行yield value语句又停止。此时yield value会输出"got:aaa",然后挂起;
    3.通过g.send(3),会重复第2步,最后输出结果为"got:3";
    4.当我们g.send("e")时,程序会执行break,然后退出循环,最后整个函数执行完毕,所以会得到StopIteration异常;

    throw()
    用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。throw()后直接抛出异常并结束程序,或者消耗掉一个yield,或者在没有下一个yield的时候直接进行到程序的结尾。

    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"之前;
    2.由于执行了g.throw(ValueError),所以会跳过所有后续的try语句,也就是说yield "normal value 2"不会被执行,然后进入到except语句,打印出"we got ValueError here",然后再次进入到while语句部分,消耗一个yield,,所以会输出normal value;
    3.print(next(g)),会执行yield "normal value 2"语句,并停留在执行完该语句后的位置;
    4.g.throw(TypeError):会跳出try语句,从而print("here")不会被执行,然后执行break语句,跳出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
    
    
    lst = ["aaadf", [1, 2, 3], [5, [6, [8, 9]], "ddf"], 7]
    for num in flatten(lst):
        print(num)
    

    如果理解起来有点儿困难,那么把print语句的注释打开在进行查看就比较明了了。
    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
    

    此时,我们可以采用yield from语句来减少工作量。

    def outer2():
        yield from inner()
    

    当然yield from语句的重点是帮我们自动处理内层之间的异常问题。

    总结:
    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);

    终极例子:通过yield在单线程下实现并发运算的效果

    import time
    
    
    def consumer(name):
        print("%s 准备吃包子啦!" % name)
        while True:
            baozi = yield
    
            print("包子[%s]来了,被[%s]吃了!" % (baozi, name))
    
    
    def producer(name):
        c = consumer("A")
        c2 = consumer("B")
        c.__next__()
        c2.__next__()
        print("老子开始准备包子啦!")
        for i in range(10):
            time.sleep(1)
            print("做了2个包子!")
            c.send(i)
            c2.send(i)
    
    
    producer("pretty")
    

    其运行结果为:

    A 准备吃包子啦!
    B 准备吃包子啦!
    老子开始准备包子啦!
    做了2个包子!
    包子[0]来了,被[A]吃了!
    包子[0]来了,被[B]吃了!
    做了2个包子!
    包子[1]来了,被[A]吃了!
    包子[1]来了,被[B]吃了!
    做了2个包子!
    包子[2]来了,被[A]吃了!
    包子[2]来了,被[B]吃了!
    做了2个包子!
    包子[3]来了,被[A]吃了!
    包子[3]来了,被[B]吃了!
    做了2个包子!
    包子[4]来了,被[A]吃了!
    包子[4]来了,被[B]吃了!
    做了2个包子!
    包子[5]来了,被[A]吃了!
    包子[5]来了,被[B]吃了!
    做了2个包子!
    包子[6]来了,被[A]吃了!
    包子[6]来了,被[B]吃了!
    做了2个包子!
    包子[7]来了,被[A]吃了!
    包子[7]来了,被[B]吃了!
    做了2个包子!
    包子[8]来了,被[A]吃了!
    包子[8]来了,被[B]吃了!
    做了2个包子!
    包子[9]来了,被[A]吃了!
    包子[9]来了,被[B]吃了!
    
    Process finished with exit code 0
    
  • 相关阅读:
    Android Xmpp协议讲解
    IOS 教程以及基础知识
    android的快速开发框架集合
    Android项目快速开发框架探索(Mysql + OrmLite + Hessian + Sqlite)
    afinal logoAndroid的快速开发框架 afinal
    Android 快速开发框架:ThinkAndroid
    2020.12.19,函数式接口,函数式编程,常用函数式接口,Stream流
    2020.12.18 网络编程基础,网络编程三要素,TCP通信,Socket类,ServerSocket
    2020.12.16,Properties,Buffer,InputStreamReader
    2020.12.15 IO流,字节流,字符流,流异常处理
  • 原文地址:https://www.cnblogs.com/love9527/p/8894161.html
Copyright © 2020-2023  润新知