generator包括生成器和带yield的generator函数。

写了一个生成杨辉三角的小例子:

# -*- coding:utf-8 -*-


def triangles():
    l = [1]
    while True:
        yield l
        nl = list()
        for i in range(len(l) + 1):
            if i == 0 or i == len(l):
                nl.append(1)
            else:
                nl.append(l[i - 1] + l[i])
        l = nl
        # N = N + [0]
        # N = [N[i - 1] + N[i] for i in range(len(N))]


# 期待输出:
# [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]
n = 0
results = []
for t in triangles():
    print(t)
    results.append(t)
    n = n + 1
    if n == 10:
        # print(t)
        break
if results == [
    [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]
]:
    print('测试通过!')
else:
    print('测试失败!')
print(triangles())
g = (i for i in range(5))
print(g)

output:

[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]
测试通过!
<generator object triangles at 0x0000000002E1D3A8>
<generator object <genexpr> at 0x0000000002E1D3A8>

 

 posted on 2018-12-12 14:14  アルタイル  阅读(194)  评论(0编辑  收藏  举报