python中生成器,,1.简介通过列表生成


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, 14     while n < max:5         print b6         a, b = b, a + b7         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 cnt10 print next(cnt)11 print next(cnt)12 print next(cnt)13 14 # output15 # <generator object create_counter at 0x0000000001D141B0>16 # create counter17 # 118 # increment n19 # 220 # increment n21 # 3

python中生成器

评论关闭