python基础-生成器

来源:互联网 发布:委托网络国债基金产品 编辑:程序博客网 时间:2024/05/21 09:08

生成器是根据某种算法得出的一系列元素,需要用到该元素,才会生成出来,比列表节省内存空间。生成器相当于保存算法,授人以渔,列表之类的是授人以鱼。


第一种创建生成器的方法:

1、gen = (x **2  for x in range(5))
type(gen)
<class 'generator'>


通过next()函数得到生成器的每个值

next(gen)
0
next(gen)
1
next(gen)
4
next(gen)
9
next(gen)
16
next(gen)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration


不过一般用for循环来使用生成器:

gen2 = (x * 9  for x in range(3))
for a in gen2:
    print(a)
    
0
9
18


第二种创建生成器的方法:

def gen4(num):
    for a in range(num):
        yield a


调用了这个函数,才会返回一个生成器对象,判断是否是生成器对象

>>>type(gen4)<class 'function'>>>>type(gen4(1))<class 'generator'>

>>>from types import GeneratorType>>>isinstance(gen4,GeneratorType)False>>>isinstance(gen4(1),GeneratorType)True


生成器的执行流程:遇到yield语句后返回,下次调用在上次返回处的下一语句开始执行。

def gen5():
    yield 1
    print('aaa')
    print('bbb')
    yield 2


rr = gen5()
next(rr)
1
next(rr)
aaa
bbb
2

有个疑问,为啥在next()函数直接用gen5()的时候是这样的?

>>>next(gen5())1>>>next(gen5())1

原来这样的话,是两次调用了gen5(),每次返回了一个生成器,调用两次,就返回两个,然后各自使用next()函数,各自都是首次调用next()函数,就返回1



0 0
原创粉丝点击