生成器

作者: Modelstrategy | 来源:发表于2017-12-15 21:57 被阅读0次
    # 生成器
    
    g = (i * i for i in range(10) if i % 2 == 0)
    for i in g:
        print(i)
    
    
    # 用生成器实现斐波拉契数列
    
    def fib(num):
        n, a, b = 0, 0, 1
        while n < num:
            yield b
            a, b = b, b + a
            n += 1
    
    for i in fib(10):
        print(i)
    
    # 用生成器实现杨辉三角
    
    def pascal_triangle():
        L = [1]
        while 1:
            yield L
            L.append(0)    # 卧槽,这点完全想不到!
            L = [L[i - 1] + L[i] for i in range(len(L))]
    
    n = 0
    for i in pascal_triangle():
        print(i)
        n+=1
        if n == 10:
            break
    

    相关文章

      网友评论

          本文标题:生成器

          本文链接:https://www.haomeiwen.com/subject/cekjwxtx.html