• python生成器


    生成器

    是一类特殊的迭代器,它是可以自己记录当前迭代对象的迭代器,可以配合next()方法使用

    创建生成器的方法:

    将列表生成[] 改为()

    In [8]: l = [x**2 for x in range(5)]
    
    In [9]: l
    Out[9]: [0, 1, 4, 9, 16]
    
    In [10]: G = (x**2 for x in range(5))
    
    In [11]: G
    Out[11]: <generator object <genexpr> at 0x00E29750>
    
    In [12]: next(G)
    Out[12]: 0
    
    In [13]: next(G)
    Out[13]: 1
    
    In [14]: next(G)
    Out[14]: 4
    
    In [15]: next(G)
    Out[15]: 9
    
    In [16]: next(G)
    Out[16]: 16
    
    In [17]: next(G)
    ---------------------------------------------------------------------------
    StopIteration                             Traceback (most recent call last)
    <ipython-input-17-b4d1fcb0baf1> in <module>()
    ----> 1 next(G)
    
    StopIteration:

    In [18]: G = (x**2 for x in range(5))

    In [20]: for x in G:
    ...: print(x)
    ...:
    0
    1
    4
    9
    16

    
    

    In [21]:

     

    创建生成器的第二种方法:

    def fib(n):
        current = 0
        num1 = 0
        num2 = 1
        while current < n:
            num = num1
            num1, num2 = num2, num1 + num2
            current += 1
            yield num

    In [25]: G = f(5)

    In [26]: next(G)
    Out[26]: 0

    In [27]: next(G)
    Out[27]: 1

    In [28]: next(G)
    Out[28]: 1

    In [29]: next(G)
    Out[29]: 2

    In [30]: next(G)
    Out[30]: 3

    In [31]: next(G)

    ---------------------------------------------------------------------------
    StopIteration Traceback (most recent call last)
    <ipython-input-31-b4d1fcb0baf1> in <module>()
    ----> 1 next(G)

    StopIteration:

    • 使用了yield关键字的函数不再是函数,而是生成器。(使用了yield的函数就是生成器)
    • yield关键字有两点作用:
      • 保存当前运行状态(断点),然后暂停执行,即将生成器(函数)挂起
      • 将yield关键字后面表达式的值作为返回值返回,此时可以理解为起到了return的作用
    • 可以使用next()函数让生成器从断点处继续执行,即唤醒生成器(函数)
    • Python3中的生成器可以使用return返回最终运行的返回值,而Python2中的生成器不允许使用return返回一个返回值(即可以使用return从生成器中退出,但return后不能有任何表达式)。
    • 我们除了可以使用next()函数来唤醒生成器继续执行外,还可以使用send()函数来唤醒执行。使用send()函数的一个好处是可以在唤醒的同时向断点处传入一个附加数据。

      例子:执行到yield时,gen函数作用暂时保存,返回i的值; temp接收下次c.send("python"),send发送过来的值,c.next()等价c.send(None)

    LESS IS MORE !
  • 相关阅读:
    文件操作与函数
    编码格式
    if、while、for快速掌握
    运算符、数据类型、数据结构
    正则表达式
    面向对象--属性
    面向对象--对象的创建
    函数的内置属性
    类型检查
    函数表达式 及 闭包
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/7795086.html
Copyright © 2020-2023  润新知