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

    1.简介

    通过列表生成式,我们可以直接创建一个列表,但是受到内存的限制,列表容量肯定是有限的。

    如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?

    在Python中,这种一边循环一边计算的机制,称为生成器:generator。

    2.示例

    2.1列表生成式的[]改成(),就创建了一个generator:

    1 s = (x * x for x in range(5))
    2 print(s)  # <generator object <genexpr> at 0x02474A80>
    3 # 可以通过next(s)不断获取返回值;或者使用for循环
    4 for x in s:
    5     print(x)

    2.2yield关键字

    1 # 非波拉契数列:
    2 def fib(max):
    3     n, a, b = 0, 0, 1
    4     while n < max:
    5         print b
    6         a, b = b, a + b
    7         n = n + 1

    使用yield 关键字:

     1 # 把fib函数变成generator,只需要把print b改为yield b.
     2 def fib1(max):
     3     n, a, b = 0, 0, 1
     4     while n < max:
     5         yield b
     6         a, b = b, a + b
     7         n = n + 1
     8 
     9 f = fib1(6)
    10 print f               # <generator object fib1 at 0x026E4B20>
    11 for x in f:
    12     print x

    说明:

    1.generator和函数的执行流程不一样。

    2.函数是顺序执行,遇到return语句或者最后一行函数语句就返回。

    3.generator的函数在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

    例如该生成器:

    第10行首次调用该生成器,运行到yield n停止(对应结果为16,17行);11行从yield n继续,由于是while循环体,在遇到yield n后再次停止(对应结果为18,19行);

    12行与11行类似。

     1 def create_counter(n):
     2     print "create counter"
     3     while True:
     4         yield n
     5         print 'increment n'
     6         n += 1
     7 
     8 cnt = create_counter(1)
     9 print cnt
    10 print next(cnt)
    11 print next(cnt)
    12 print next(cnt)
    13 
    14 # output
    15 # <generator object create_counter at 0x0000000001D141B0>
    16 # create counter
    17 # 1
    18 # increment n
    19 # 2
    20 # increment n
    21 # 3
  • 相关阅读:
    sort_action
    jedis
    ClassNotFoundException
    mysql-test-run.pl
    mysql 5.6 bug
    The basic principle of test case 修改引擎
    mysql 执行计划走索引
    mysql 执行计划走索引
    14.1.2 Checking InnoDB Availability 检查InnoDB 可用性:
    14.1.2 Checking InnoDB Availability 检查InnoDB 可用性:
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/7380481.html
Copyright © 2011-2022 走看看