zoukankan      html  css  js  c++  java
  • 使用 yield生成迭代对象函数

    https://www.cnblogs.com/python-life/articles/4549996.html
    https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143178254193589df9c612d2449618ea460e7a672a366000

    def fab(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a+b
            n = n + 1
    
    >>> fab
    <function fab at 0x7f6ab605aea0>
    #函数
    
    >>> fab(5)
    <generator object fab at 0x7f6ab5fe4ca8>
    # 迭代对象
    
    
    >>> for i in fab(5):
    ...     print(i)
    ... 
    1
    1
    2
    3
    5
    # 打印迭代对象
    
    简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。
    
    >>> f = fab(5)
    >>> next(f)
    1
    >>> next(f)
    1
    >>> next(f)
    2
    >>> next(f)
    3
    >>> next(f)
    5
    >>> next(f)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    
    可以直接作用于for循环的数据类型有以下几种:
    一类是集合数据类型,如list、tuple、dict、set、str等; 一类是generator,包括生成器和带yield的generator function。
    这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。可以使用isinstance()判断一个对象是否是Iterable对象:
    
    # 凡是可作用于for循环的对象都是Iterable类型;
    
    # 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
    
    # 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
    
  • 相关阅读:
    Codeforces 1072
    XDOJ 1046
    BZOJ 1002
    BZOJ 1001
    BZOJ 1500/Luogu 2042
    nowcoder 211B
    BZOJ 3224
    BZOJ 1150
    POJ 2442
    二叉堆和二叉搜索树进阶
  • 原文地址:https://www.cnblogs.com/liujitao79/p/8572326.html
Copyright © 2011-2022 走看看