python中的迭代器和生成器

来源:互联网 发布:c语言编写小游戏 编辑:程序博客网 时间:2024/06/06 03:47

1、列表生成式

生成器:只有在调用时才会生成相应的数据,只记录当前位置,只有一个__next__()方法。next()

# Author:danchengdef fib(max):    n, a, b = 0, 0, 1    while n < max:        #print(b)        yield b        a, b = b, a + b   #这句话相当于t(b, a + b)   a = t[0]   b = t[1]        n = n + 1    return 'done'     #return 是异常时打印的消息# f = fib(10)# print(f.__next__())# print(f.__next__())# print(f.__next__())# print(f.__next__())# for i in f:#     print(f.__next__())、g = fib(6)while True:    try:        x = next(g)        print('g:', x)    except StopIteration as e:        print('Generator return value', e.value)        break

2、迭代器:

凡是可作用于for循环的对象都是可迭代对象

凡是可作用于next()函数的对象都是迭代器对象

集合数据类型如listdictstr等是可迭代对象但不是迭代器对象,不过可以通过iter()函数获得一个Iterator对象。



原创粉丝点击