可迭代对象、迭代器、生成器的理解

2019-05-12 21:28:13阅读 31评论 0

名词解释

1.可迭代对象

有iter方法的对象为可迭代对象,如列表、字符串

    list=[i for i in range(10)]  
    print(list)

结果:

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  

    Process finished with exit code 0

验证是否时可迭代对象

    from collections import Iterable  
    list=[i for i in range(10)]  
    print(isinstance(list,Iterable))

结果:

    True  

    Process finished with exit code 0

2.迭代器

有iter方法,并且有next方法的对象

    from collections import Iterable,Iterator  

    list1=[i for i in range(10)]#生成一个列表  
    list2=(i for i in range(10))#生成一个迭代器  
    print(isinstance(list1,Iterator))  
    print(isinstance(list2,Iterator))

结果:

    False  
    True  

    Process finished with exit code 0

3.生成器

返回迭代器的函数,只能用于迭代操作,其实就是就是一个迭代器

    def fab():  
        a=1  
        b=1  
        while True:  
            a,b=b,a+b  
            yield a  
    f=fab()  
    print(next(f))  
    print(next(f))  
    print(next(f))  
    print(next(f))  
    print(next(f))

结果:

    1  
    2  
    3  
    5  
    8  

    Process finished with exit code 0

4.yield相关的生产者消费者模型(协程)

    def eater():  
        while True:  
            food = yield#yield相当于return,同时也可以接收send()传进来的值  
            print("A dog is eating a %s" % food)  

    def producer(num):  
        num=num#接收参数num  
        e=eater()  
        e.__next__()  
        for  i in range(num):  
            food="baozi"+str(i)#生产包子  
            print("producer have producted a %s"%food)  
            ##############################  
            e.send(food)#把食品传送给消费者,这里的send有两个作用:1.将e执行__next__方法2.将参数传递给e里的yield  

    producer(10)

结果:

    producer have producted a baozi0  
    A dog is eating a baozi0  
    producer have producted a baozi1  
    A dog is eating a baozi1  
    producer have producted a baozi2  
    A dog is eating a baozi2  
    producer have producted a baozi3  
    A dog is eating a baozi3  
    producer have producted a baozi4  
    A dog is eating a baozi4  
    producer have producted a baozi5  
    A dog is eating a baozi5  
    producer have producted a baozi6  
    A dog is eating a baozi6  
    producer have producted a baozi7  
    A dog is eating a baozi7  
    producer have producted a baozi8  
    A dog is eating a baozi8  
    producer have producted a baozi9  
    A dog is eating a baozi9  

    Process finished with exit code 0

定义范围

可迭代对象>迭代器>生成器

还没有评论,来说两句吧