• 生成器


    生成器(generator)

    生成器指的是生成器对象,可以由生成器表达式得到,也可以使用yield关键字得到一个生成器,调用这个函数得到一个生成器对象;

    生成器函数

    函数体中包含yield语句的函数,返回生成器对象,生成器对象是一个可迭代对象,是一个迭代器,生成器的函数体不会立即执行,next(generator)会从函数的当前位置向后执行到之后碰到的第一个yield语句,会弹出yield的值,并暂停函数执行;没有多余的yield语句能被执行,继续调用next函数,会抛出StopIteration异常;

    def inc():
        for i in range(5):
            yield  i
    
    print(type(inc))
    print(type(inc()))
    x = inc()
    print(type(x))
    print(next(x))
    for m in x:
        print(m,'*')
    for m in x:
        print(m,'**')
    

    生成器函数可以使用next函数多次执行,每次返回一个值;

    def gen():
        print('line 1')
        yield 1
        print('line 2')
        yield 2
        print('line 3')
        return 3
    next(gen())
    next(gen())
    g = gen()
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g, 'End'))
    

    生成器函数中,使用多个yield语句,执行一次后会暂停执行,把yield表达式的值返回;在次执行会执行到一个yield语句;return语句依然可以终止函数运行,但return语句的返回值不能获取到;return会导致无法继续获取下一个值,抛出StopIteration异常;如果函数没有显示return语句,如果生成器函数执行到结尾,一样会抛出StopIteration异常;

    生成器的应用:

    计数器

    def inc():
        def counter():
            i = 0
            while True:
                i += 1
                yield i
        c = counter()
        return lambda : next(c)
    
    foo = inc()
    print(foo())
    print(foo())
    print(foo())
    
    def inc():
        def counter():
            i = 0
            while True:
                i += 1
                yield i
    
        c = counter()
    
        def _inc():
            return next(c)
        return _inc
    
    foo = inc()
    print(foo())
    print(foo())
    print(foo())
    

    递归问题

    pre = 0
    cur = 1
    print(pre,cur,end=' ')
    
    def fib1(n,pre=0,cur=1):
        pre,cur = cur,pre+cur
        print(cur,end=' ')
        if n == 2:
            return
        fib1(n-1,pre,cur)
    
    fib1(8)

    yield from是python3.3出现的新语法

    def counter(n):
        for x in range(n):
            yield x
    
    def inc(n):
        yield from counter(n)
    
    foo = inc(10)
    print(next(foo))
    print(next(foo))
    
    foo1 = counter(10)
    print(next(foo1))
    print(next(foo1))
    
  • 相关阅读:
    【Spring学习】Spring的源码解析之路 ——【step1】基础环境配置 + IDEA快捷键整理
    【Spring学习】Spring的源码解析之路
    【Android端】【日志收集上报SDK相关内容测试的方案梳理总结】
    【codelife 阿里技术文章分享——读后感】
    【python深入】map/reduce/lambda 内置函数的使用
    【python深入】单例模式
    【python深入】装饰器理解及使用
    【python深入】collections-Counter使用总结
    【python深入】dict和list实现排序:sorted()和lambda的使用
    选择排序
  • 原文地址:https://www.cnblogs.com/52py/p/7692726.html
Copyright © 2020-2023  润新知