• Python生成器


    参考http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000

     1 # -*- coding: utf-8 -*-
     2 
     3 #把列表生成式的[]改为(),就创建了一个generator
     4 L = [x * x for x in range(10)]
     5 #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
     6 g = (x * x for x in range(10))
     7 #next(g)通过next()函数获得generator的下一个返回值,直到计算到最后一个元素,抛出StopIteration错误
     8 
     9 # 因为generator也是可迭代对象,可使用for循环,等价于不断调用next(g)
    10 for n in g:
    11     print n,
    12 # 0 1 4 9 16 25 36 49 64 81
    13 
    14 # 创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误
    15 # 如果算法比较复杂,用类似列表生成式的for循环无法实现generator,还可以用函数来实现generator
    16 # 用函数实现generator,把fib函数变成generator,只需要把print(b)改为yield b就可以了
    17 # generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
    18 # 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
    19 # 我们在循环过程中不断调用yield,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。
    20 # 同样的,把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代。
    21 
    22 # 举个例子:
    23 def odd():
    24     print('step 1')
    25     yield 1
    26     print('step 2')
    27     yield(3)
    28     print('step 3')
    29     yield(5)
    30 # o=odd()
    31 # next(o)
    32 # step 1
    33 # 1
    34 # next(o)
    35 # step 2
    36 # 3
    37 # next(o)
    38 # step 3
    39 # 5
    40 # next(o)
    41 # Traceback (most recent call last):
    42 #   File "<stdin>", line 1, in <module>
    43 # StopIteration
    44 
    45 # 普通函数实现斐波那契数列
    46 def fib(max):
    47     n, a, b = 0, 0, 1
    48     while n < max:
    49         print(b),
    50         a, b = b, a + b
    51         n = n + 1
    52     return 'done'
    53 # fib(6)
    54 # 1 1 2 3 5 8
    55 
    56 # generator实现斐波那契数列
    57 def fib(max):
    58     n, a, b = 0, 0, 1
    59     while n < max:
    60         yield b
    61         a, b = b, a + b
    62         n = n + 1
    63 for n in fib(6):
    64     print(n),
    65 # 1 1 2 3 5 8
  • 相关阅读:
    SQL查询语句中,any和all有什么区别?
    $(function(){...});
    在ASP.NET中TextBox和TextBoxFor的区别以及ValidationMessageFor的作用以及EditorFor等的作用和用法什么?
    Brt课程设计day3
    Brt课程设计day2
    day1
    .net 高级写法总结
    可能是目前最完整的前端框架 Vue.js 全面介绍
    redis live 如何安装
    百万级PHP网站架构工具箱
  • 原文地址:https://www.cnblogs.com/hslzju/p/5632211.html
Copyright © 2020-2023  润新知