zoukankan      html  css  js  c++  java
  • python基础---生成器

    可迭代对象里面,都可以使用一个__iter__(),函数返回一个迭代器

    迭代器本身只是一个内存地址 ,使用next(),__next__(),send().可以从这里拿值

    在 Python 中,使用了 yield 的函数被称为生成器(generator)。

    跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。

    在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。

    调用一个生成器函数,返回的是一个迭代器对象。

    挂起,这是生成器函数最要记住的特点

    import time
    def prod():
    for baozi in range(100):
    print('开始生产包子',' ')
    time.sleep(0.3)
    yield '天下第一包子当天生产的第%s个包子'%baozi
    time.sleep(0.3)
    print('开始卖包子',' ')
    Baozi=prod()
    for coms in range(100):
    time.sleep(1)
    print('第%s位顾客上门了'%coms)
    print('第%s位顾客吃了' %coms,Baozi.__next__(),' ')


    以下实例使用 yield 实现斐波那契数列
     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()
    

      输出:0 1 1 2 3 5 8 13 21 34 55

  • 相关阅读:
    Jzoj4822 完美标号
    Jzoj4822 完美标号
    Jzoj4792 整除
    Jzoj4792 整除
    Educational Codeforces Round 79 A. New Year Garland
    Good Bye 2019 C. Make Good
    ?Good Bye 2019 B. Interesting Subarray
    Good Bye 2019 A. Card Game
    力扣算法题—088扰乱字符串【二叉树】
    力扣算法题—086分隔链表
  • 原文地址:https://www.cnblogs.com/yuanji2018/p/8964201.html
Copyright © 2011-2022 走看看