生成器 --使用生成器来创建新的迭代模式

目的:实现一个自定义的迭代模式,使其区别与常见的内建函数(即range()、reversed()等)

解决方案:使用生成器函数,实现一种新的迭代模式
def frange(start, stop, increment):
    x = start
    while x < stop:
        yield x
        x += increment

# 使用for循环对其迭代
for n in frange(0, 1, 0.25):
    print(n)
Outs:
0
0.25
0.5
0.75

# 使用 list()访问
print(list(frange(0, 1, 0.25)))
Outs:
[0, 0.25, 0.5, 0.75]

下面来看下生成器函数的底层机制是如何运转的:

def countdown(n):
    while n>0:
        yield n
        n -= 1
    print('Done!')

c = countdown(3)  # 创建一个生成器
c
Out[9]: 

next(c)
Out[10]: 3
next(c)
Out[11]: 2
next(c)
Out[12]: 1
next(c)
Done!
Traceback (most recent call last):
StopIteration
关于生成器:

1、函数中只要出现了yield语句就会将其转变成一个生成器。与普通函数不同,生成器只会在响应迭代操作时才运行;
2、生成器函数只会在响应迭代过程中的"next"操作时才会运行;一旦生成器函数返回,迭代也就停止了;
3、生成器是可以迭代的(next()或者for),和迭代器一样迭代结束时,报StopIteration。

你可能感兴趣的:(生成器 --使用生成器来创建新的迭代模式)