Python的迭代器与生成器
·
迭代器
迭代器是一个可以记住遍历位置的对象,迭代器对象从第一个元素开始访问,直到所有元素被访问完毕,迭代器只可以向前访问,不可向后退。
迭代器的两种基本方法:iter() 和 next()
字符串,列表,元组都可以创建迭代器
list1 = [0,1,2,3,4,5]
it = iter(list1)
print(next(it)) # 0
print(next(it)) # 1
迭代器还可以通过循环来进行遍历
list1 = [0,1,2,3,4,5]
it = iter(list1)
for x in it:
print(x,end=' ') # 0 1 2 3 4 5
也可以使用next()
list1 = [0,1,2,3,4,5]
it = iter(list1)
while True:
try:
print(next(it),end='') # 012345
except StopIteration:
break
StopIteration
StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况,在 next() 方法中我们可以设置在完成指定循环次数后触发 StopIteration 异常来结束迭代
生成器
在 Python 中,使用了 yield 的函数被称为生成器,yield 是一个关键字,用于定义生成器函数,生成器函数是一种特殊的函数,可以在迭代过程中逐步产生值,而不是一次性返回所有结果
def countdown(n):
while n > 0:
yield n
n = n - 1
gener = countdown(5)
print(next(gener)) # 5
print(next(gener)) # 4
print(next(gener)) # 3
for x in gener:
print(x,end=' ') # 2 1
countdown 函数是一个生成器函数。它使用 yield 语句逐步产生从 n 到 1 的倒数数字。在每次调用 yield 语句时,函数会返回当前的倒数值,并在下一次调用时从上次暂停的地方继续执行,生成器函数的优势是它们可以按需生成值,避免一次性生成大量数据并占用大量内存。
斐波那契数列
斐波那契数列是一个数字序列,其中每个数字是前两个数字的总和,通常以0和1作为起始值。具体定义为:F(1) = 0,F(2) = 1,且对于n ≥ 3,有F(n) = F(n-1) + F(n-2)。这个数列的前几项为:0、1、1、2、3、5、8、13、21、34等
def fibonacci(n):
a, b, counter = 0, 1, 0
while True:
if counter > n:
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10)
while True:
try:
print(next(f), end=" ") # 0 1 1 2 3 5 8 13 21 34 55
except StopIteration:
break
简单讲解一下
第1次调用 next(f):
→ yield a (输出0)
→ 暂停 (后面的 a,b = ... 还没执行!)
第2次调用 next(f):
→ 从暂停处继续 a,b = b,a+b (a变成1, b变成1)
→ counter += 1
→ 回到 while 开头
→ yield a (输出1)
→ 暂停
第3次调用 next(f):
→ 从暂停处继续 a,b = b,a+b (a变成1, b变成2)
→ counter += 1
→ 回到 while 开头
→ yield a (输出1)
→ 暂停
yield 和 return 最大的不同就是,return 是直接返回所有,yield 是返回逐步返回。
更多推荐


所有评论(0)