• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
火磷
Memory will fade,but not notes.
博客园    首页    新随笔    联系   管理    订阅  订阅
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

 

posted on 2017-08-17 10:59  火磷  阅读(213)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3