Fibonacci数列:除第一个与第二个数之外,其余数均由前两个数相加得到:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

通过生成器,程序如下:

def fib(max):
    m, a, b = 0, 0, 1
    while m < max:
        yield b
        a, b = b ,a+b
        m = m+1
    return 'done'

要将其结果打印出来:

g = fib(6)
while True:
    try:
        x = next(g)
        print('g:', x)
    except StopIteration as e:
        print('Generator return value:', e.value)
        break

杨辉三角:

# 杨辉三角
def triangles():
    L = [1,0]       # 此列表的末尾有 0 元素
    while True:
        yield L[:-1]        # 0 元素不让其显示,只显示前面的元素
        L = [1] + [L[x] + L[x-1] for x in range(1, len(L))] + [0]

n = 0
for t in triangles():
    print(t)
    n = n+1
    if n == 10:
        break

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]