Discuss / Python / 生成器

生成器

Topic source

landingguymmm

#1 Created at ... [Delete] [Delete and Lock User]

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

def triangles():

    a=[1]

    while True: #无限循环

        yield a

        a = [1] + [a[i]+a[i+1] for i in range(len(a)-1)] + [1]   

#多个列表相加,最后得到所有列表元素集合的总列表

#到这里只是定义了这个函数

n = 0

results = []

for t in triangles(): #用迭代 来替换 用next()调用每组输出值。

    results.append(t)  #没看懂?岂不是将输出的列表又加起来?!!!明白了!!! results是一个大集合 ,用于判断后面测试通过还是失败。

    n = n + 1

    if n == 10:    #只输出十组

        break

for t in results: #输出并打印出每一组

    print(t)

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('测试失败!')

Adorkable1

#2 Created at ... [Delete] [Delete and Lock User]

    a = [1] + [a[i]+a[i+1] for i in range(len(a)-1)] + [1]   ,这一句如果a的长度是1的时候,前面的a[i+1]不是就越界了吗?


  • 1

Reply