您的当前位置:首页正文

Python 生成器-generator

来源:图艺博知识网

生成器的概念

生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到StopIteration异常结束。

  1. 列表与生成器区别
#普通列表
gen = [x*2 for x in range(5)]
print('普通列表 := %s ' % gen)
#生成器
gen = (x*2 for x in range(5))
print('生成器 := %s' % gen)
普通列表 := [0, 2, 4, 6, 8] 
生成器 := <generator object <genexpr> at 0x000000000505A200>
  1. 生成器实例1
#例子1
def odd(max_n):
    n=1
    while n <= max_n:
        yield n
        n+=2

for o in odd(5):
    print(o)
1
3
5
  1. 生成器实例2
#著名的斐波拉契数列
def fib(max_n):
    a,b = 1,2
    while b <= max_n :
        yield a
        a,b = b,a+b
        
for o in fib(100):
    print(o)

1
2
3
5
8
13
21
34
55
  1. 生成器实例3 (next调用 )
#实践next方法
def odd(max_n):
    n=1
    while n <= max_n:
        yield n
        n+=2

func = odd(5)
print(func.__next__())
print(func.__next__())
print(func.__next__())
print(func.__next__())

1
3
5



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-16-69e5c7ba2b2c> in <module>()
     10 print(func.__next__())
     11 print(func.__next__())
---> 12 print(func.__next__())


StopIteration: 
  1. yield 与 return
    在一个生成器中,如果没有return,则默认执行到函数完毕时返回StopIteration;
    如果遇到return,如果在执行过程中 return,则直接抛出 StopIteration 终止迭代。
#带有return的生成器方法
def gen():
    yield 1
    yield 2
    return 
    yield 3

for o in gen():
    print(o)

print('=====漂亮的分隔符=====')
test = gen()
print(test.__next__())
print(test.__next__())
print(test.__next__())
1
2
=====漂亮的分隔符=====
1
2
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-21-804ab8c50d0c> in <module>()
     13 print(test.__next__())
     14 print(test.__next__())
---> 15 print(test.__next__())
     16 
     17 

StopIteration: 
  1. 生成器支持的方法
help(odd(5))
Help on generator object:

odd = class generator(object)
 |  Methods defined here:
 |  
 |  __del__(...)
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  close(...)
 |      close() -> raise GeneratorExit inside generator.
 |  
 |  send(...)
 |      send(arg) -> send 'arg' into generator,
 |      return next yielded value or raise StopIteration.
 |  
 |  throw(...)
 |      throw(typ[,val[,tb]]) -> raise exception in generator,
 |      return next yielded value or raise StopIteration.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  gi_code
 |  
 |  gi_frame
 |  
 |  gi_running
 |  
 |  gi_yieldfrom
 |      object being iterated by yield from, or None
  1. close方法

手动关闭生成器函数,后面的调用会直接返回StopIteration异常。

# close() 手动关闭生成器函数,后面的调用会直接返回StopIteration异常。

def gen():
    yield 1
    yield 2
    yield 3

g=gen()
print(g.__next__())
g.close()
print(g.__next__())


1



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-27-3e8b7df380d6> in <module>()
      8 print(g.__next__())
      9 g.close()
---> 10 print(g.__next__())
     11 
     12 


StopIteration: 
  1. send 方法

生成器函数最大的特点是可以接受外部传入的一个变量,并根据变量内容计算结果后返回。

# send()
# 生成器函数最大的特点是可以接受外部传入的一个变量,并根据变量内容计算结果后返回。

def gen():
    value='atp'
    while True:
        receive=yield value
        if receive=='end':
            break
        value = '%s' % receive

g=gen()
print(g.send(None))     
print(g.send('abc'))
print(g.send(3))
print(g.send('end'))

atp
abc
3



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-30-e5080153cccf> in <module>()
     14 print(g.send('abc'))
     15 print(g.send(3))
---> 16 print(g.send('end'))


StopIteration: 

执行流程:

  1. 通过g.send(None)或者next(g)可以启动生成器函数,并执行到第一个yield语句结束的位置。此时,执行完了yield语句,但是没有给receive赋值。yield value会输出初始值0注意:在启动生成器函数时只能send(None),如果试图输入其它的值都会得到错误提示信息。
  2. 通过g.send(‘abc’),会传入abc,并赋值给receive,然后计算出value的值,并回到while头部,执行yield value语句有停止。此时yield value会输出”abc”,然后挂起。
  3. 通过g.send(3),会重复第2步,最后输出结果为”3″
  4. 当我们g.send(‘e’)时,程序会执行break然后推出循环,最后整个函数执行完毕,所以会得到StopIteration异常。
  1. throw方法

用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。throw()后直接跑出异常并结束程序.

# throw()
# 用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。
# throw()后直接跑出异常并结束程序.

def gen():
    while True: 
        try:
            yield 'normal value'
            yield 'normal value 2'
            print('here')
            yield 'normal value 3'

        except ValueError:
            print('we got ValueError here')
        except TypeError:
            print('we got TypeError here')
            break
 
g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))

normal value
we got ValueError here
normal value
normal value 2
we got TypeError here



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-38-fbedd6d510de> in <module>()
     21 print(g.throw(ValueError))
     22 print(next(g))
---> 23 print(g.throw(TypeError))


StopIteration: 

解释:

  1. print(next(g)):会输出normal value,并停留在yield ‘normal value 2’之前。
    由于执行了g.throw(ValueError),所以会跳过所有后续的try语句,也就是说yield ‘normal value 2’不会被执行,然后进入到except语句,打印出we got ValueError here。然后再次进入到while语句部分,消耗一个yield,所以会输出normal value。
  2. print(next(g)),会执行yield ‘normal value 2’语句,并停留在执行完该语句后的位置。g.throw(TypeError):会跳出try语句,从而print(‘here’)不会被执行,然后执行break语句,跳出while循环,然后到达程序结尾,所以跑出StopIteration异常。
def gen():
    try:
        yield 'normal value'
        yield 'normal value 2'
        print('here')
        yield 'normal value 3'

    except ValueError:
        print('we got ValueError here')
    except TypeError:
        pass
 
g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))

normal value
we got ValueError here



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-39-b846253db189> in <module>()
     13 g=gen()
     14 print(next(g))
---> 15 print(g.throw(ValueError))
     16 print(next(g))


StopIteration: 

总结

  1. 按照鸭子模型理论,生成器就是一种迭代器,可以使用for进行迭代。
  2. 第一次执行next(generator)时,会执行完yield语句后程序进行挂起,所有的参数和状态会进行保存。再一次执行next(generator)时,会从挂起的状态开始往后执行。在遇到程序的结尾或者遇到StopIteration时,循环结束。
  3. 可以通过generator.send(arg)来传入参数,这是协程模型。
  4. 可以通过generator.throw(exception)来传入一个异常。throw语句会消耗掉一个yield。
  5. 可以通过generator.close()来手动关闭生成器。
  6. next()等价于send(None)

试验1:素数生成器

#奇数生成方法
def _odd_iter(n):
    while True:
        yield n
        n = n + 2
        
#过滤掉队列中能被n整除的元素
def _not_divisible(n):
    return lambda x: x % n > 0

#素数生成器
def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it) # 构造新序列

for n in primes():
    if n < 1000:
        print(n)
    else:
        break
Top