• 技术文章 >Python技术 >Python基础教程

    python生成器创建的方法整理

    小妮浅浅小妮浅浅2021-07-22 09:38:05原创2414

    1、推导式的方法,只需将列表生成的[]改为()

    创建生成器的方法有很多。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    In [26]: L = [num * 2 for num in range(5)]

      

    In [27]: L

    Out[27]: [0, 2, 4, 6, 8]

      

    In [28]: G = (num * 2 for num in range(5))

      

    In [29]: G

    Out[29]: <generator object <funexpr> at 0x000001D62EA28248>

    2、next() 函数

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    In [30]: next(G)

    Out[30]: 0

      

    In [31]: next(G)

    Out[31]: 2

      

    In [32]: next(G)

    Out[32]: 4

      

    In [33]: next(G)

    Out[33]: 6

      

    In [34]: next(G)

    Out[34]: 8

      

    In [35]: next(G)

    ---------------------------------------------------------------------------

    StopIteration                             Traceback (most recent call last)

    <ipython-input-35-b4d1fcb0baf1> in <module>

    ----> 1 next(G)

      

    StopIteration:

    3、for循环与list,因为G已经迭代到了ipython测试的最后,所以需要重建G,否则就没有数据了。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    In [38]: G = (num * 2 for num in range(5))

      

    In [39]: for i in G:

        ...:     print(i)

        ...:

    0

    2

    4

    6

    8

      

    In [40]: list(G)

    Out[40]: []

      

    In [41]: G = (num * 2 for num in range(5))

      

    In [42]: list(G)

    Out[42]: [0, 2, 4, 6, 8]

    以上就是python生成器创建的方法整理,希望对大家有所帮助。更多编程基础知识学习:python学习网

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python生成器
    上一篇:python gevent的原理分析 下一篇:python如何使用send唤醒

    相关文章推荐

    • python生成器中的send()方法和next()方法• 神秘而强大的Python生成器精讲• 一篇文章教你如何使用Python生成器• python生成器如何实现• 解析python生成器函数的调用• 如何使用python生成器返回指定的值?• python生成器的原理探究• python生成器函数的特点• python生成器调用方法引发异常• python生成器如何进行解析• python生成器切片的实现

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网