您的位置:首页 > 编程语言 > Python开发

python中的迭代器和生成器

2017-10-05 07:40 239 查看

1、列表生成式

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

# Author:dancheng
def 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()函数的对象都是迭代器对象
集合数据类型如list、dict、str等是可迭代对象但不是迭代器对象,不过可以通过iter()函数获得一个Iterator对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: