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

    python生成器的调用理解

    小妮浅浅小妮浅浅2021-09-28 09:39:55原创1848

    1、生成器是返回迭代器的函数,只能用于迭代操作。

    2、在调用生成器运行过程中,每次遇到yield时,函数都会暂停并保存所有当前的运行信息。

    返回yield值,并在下次执行next()方法时从当前位置继续运行。调用生成器函数,返回迭代器对象。

    实例

    import sys
     
    def fibonacci(n): # 生成器函数 - 斐波那契
        a, b, counter = 0, 1, 0
        while True:
            if (counter > n):
                return
            yield a
            a, b = b, a + b
            counter += 1
    f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
     
    while True:
        try:
            print (next(f), end=" ")
        except StopIteration:
            sys.exit()

    以上就是python生成器的调用理解,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python生成器
    品易云
    上一篇:python StopIteration异常的使用 下一篇:python读取文件出现空行的解决

    相关文章推荐

    • python poetry创建虚拟环境• python poetry如何安装依赖• python中flake8是什么• python中mypy是什么• python创建链表的两种形式• python面向过程的优缺点• python面向对象编程的优缺点• python面向对象设计和面向对象编程的理解• python类属性和实例属性的区别• python迭代器的要点整理• python StopIteration异常的使用

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网