zoukankan      html  css  js  c++  java
  • 生成器

    TOC

    一、什么是生成器

    1 生成器的定义

    生成的工具
    生成器是一个‘自定义’的迭代器,本质上是一个迭代器。

    # python内置的迭代器:
    list1 = [1, 2, 3]
    iter_list = list1._iter_()  # 迭代器对象,python内置生成的迭代器
    
    
    # 自定义的迭代器
    def func(start, end, move=1):
        while start < end:
            yield start
            start += move
    
    
    iter_func = func(1, 4)
    print(iter_func.__next__())
    #可以像使用迭代器那样调用._next_()
    print(iter_func.__next__())
    
    1
    2
    
    Process finished with exit code 0

    1.2 如何实现生成器

    但凡在函数内部定义了yield,调用函数时,函数体代码不会执行,会返回函数的结果,该结果就是一个生成器。

    yield:

    • 每一次yield都会往生成器对象中添加一个值
    • yield只能在函数内部定义
    • yield可以保存函数的暂停状态

    1.2.1 yield与return的区别

    相同点:

    • 都可以返回无限制的值

    不同点:

    • yield可以返回多次值,return只能返回一次
    def func():
        print('开始准备下蛋')
        print('1---火鸡蛋1')
        yield '火鸡蛋1'
        print('2---火鸡蛋2')
        yield '火鸡蛋2'
        print('3---火鸡蛋3')
        yield '火鸡蛋3'
        print('取最后一个蛋,查看是否有')
    
    
    res = func()  # func将值给了res,那res现在就是迭代器对象
    # 注意: 当我们通过._next_()取值的时候,才会执行函数体代码
    # 迭代器对象._next_()可以写成next(),例如:
    ```python
    print(next(res))
    print(next(res))
    print(res.__next__())
    print(res.__next__())  # StopIteration报错

    1.3 生成器的应用

    1.3.1 利用生成器自定义range

    利用for+range循环取值

    # python内置的for循环方法
    for i in range(1, 11):
        print(i)
    # python2中:range(1, 5)返回的是一个列表[1, 2, 3, 4]
    # python3中:range(1, 5)返回的是一个range对象--->生成器--->迭代器
    res = range(1, 5)
    print(res)
    
    >>> range(1, 5)

    自定义range功能,创建一个自定义的生成器

    def my_range(start, end, move=1):
        while start < end:
            yield start
            start += move
    
    
    for i in my_range(1, 4):
        print(i)
    
    
    >>> 1
    >>> 2
    >>> 3
    
    Process finished with exit code 0
  • 相关阅读:
    cookie 和 session 和 session id
    getMasterRequest VS getCurrentRequest?
    drupal 7 watchdog 记录debug信息
    刷环境
    再进一步
    7zip 不见 .git
    为什么我记不住密码
    www / publish
    behat debug / class property
    drupal 网站Log
  • 原文地址:https://www.cnblogs.com/cnhyk/p/11890774.html
Copyright © 2011-2022 走看看