美文网首页
chapter5 函数进阶*3

chapter5 函数进阶*3

作者: 木果渣 | 来源:发表于2017-12-19 23:28 被阅读0次

    生成器与迭代

    ##generator
    #
    L = [x*x for x in range(10)]
    g = (x*x for x in range(10))
    print(L)
    print(g)
    
    print(next(g))
    
    for n in g:
        print(n)
    
    def fib(max):
        n, a, b = 0, 0, 1
        while n < max:
            print(b)
            a, b = b , a+b
            n += 1
        return 'done'
    
    fib(10)
    
    def fib(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b, = b, a+b
            n += 1
        return 'done'
    
    f = fib(10)
    print(f)
    
    def odd():
        print('step 1')
        yield 1
        print('step 2')
        yield(3)
        print('step 3')
        yield(5)
    
    o = odd()
    next(o)
    next(o)
    next(o)
    
    ##用生成器写杨辉三角
    def triangles():
        L = [1]
        while 1:
            yield L
            temp = [1]
            for i in range(len(L)-1):
                temp.append(L[i] + L[i+1])
            temp.append(1)
            L = temp[:]
    
    gen_list = triangles()
    print(next(gen_list))
    print(next(gen_list))
    print(next(gen_list))
    print(next(gen_list))
    print(next(gen_list))
    print(next(gen_list))
    
    n = 0
    results = []
    for t in triangles():
        print(t)
        results.append(t)
        n += 1
        if n == 10:
            break
    
    print(results)
    
    ##更好的写法
    def triangles_better():
        L = [1]
        while 1:
            yield L
            L = [L[i]+L[i+1] for i in range(len(L)-1)]
            L.insert(0, 1)
            L.append(1)
    
    def triangles_better_2():
        L = [1]
        while 1:
            yield L
                    L.append(0)
            L = [L[i]+L[i-1] for i in range(len(L))]
    
    
    better_list = triangles_better()
    print(next(better_list))
    print(next(better_list))
    print(next(better_list))
    print(next(better_list))
    print(next(better_list))
    print(next(better_list))
    print(next(better_list))
    
    
    ##Iterator
    #
    
    from collections import Iterable
    print(isinstance([], Iterable))
    print(isinstance({}, Iterable))
    print(isinstance('abc', Iterable))
    print(isinstance((x for x in range(10)), Iterable))
    
    from collections import Iterator
    print(isinstance((x for x in range(10)), Iterator))
    print(isinstance([], Iterator))
    print(isinstance({}, Iterator))
    print(isinstance('abc', Iterator))
    
    ##生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
    
    print(isinstance(iter('abc'), Iterator))
    
    
    L = [1, 2, 3, 4]
    I = iter(L)
    print(next(I))
    print(next(I))
    print(next(I))
    print(next(I))
    ##StopIteration
    print(next(I))
    
    

    相关文章

      网友评论

          本文标题:chapter5 函数进阶*3

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