JAVA网络爬虫
HttpClient

导航

 

python生成器的相关操作

  • 生成器-1

    a = (x*2 for x in range(10))
    print(next(a)) #一次生成一个值  生成到最后一个的时候还调用next直接报错
    
    # 运行结果
    0
    
  • yield函数生成器-2

    def creatNUM():
        print("----start----")
        print("----1----")
        a,b = 0,1
        for i in range(5):
            print("----2----")
            yield b    #yield有两个功能 1.暂停功能 2.反回一个值
            a,b = b,a+b
            print("----3----")
        print("----stop----")
    
    #创建一个生成器对象
    a = creatNUM()
    
    '''
    注意:
    print(next(a))
                                 next(a) <==>a.__next__()
    ret = a.__next__()
    print(ret)
    
    以上两中方式一样
    '''
    
    for num in a:
        print(num)
    
    # 运行结果
    ----start----
    ----1----
    ----2----
    1
    ----3----
    ----2----
    1
    ----3----
    ----2----
    2
    ----3----
    ----2----
    3
    ----3----
    ----2----
    5
    ----3----
    ----stop----
    
  • 生成器-3-send

    def test():
        i = 0
        while i < 5:
            temp = yield i #程序每次运行到这里的时候把i值反回 然后暂停  第二次运行的时候就变成了None 在反回i 暂停
            print(temp)    #暂停以后yield i 变成了None 
            i+=1
    t = test()
    print(t.__next__())
    print(t.__next__())
    print(t.__next__())
    
    t.send("haha") #这个哈哈就相当于 暂停以后yield i 变成了 haha
    
    # 运行结果
    0
    None
    1
    None
    2
    haha
    
  • 生成器-4-send强调

    '''
    def test():
        i = 0
        while i < 5:
            temp = yield i
            print(temp)  
            i+=1
    t = test()
    
    #第一种
    print(t.__next__())
    
    t.send("haha") 
    
    #第二种
    t.send(None)  #send必须有一个参数
    t.send("chacha") #传的值temp只会保存一次
    '''
    
    def test():
        i = 0
        while i < 5:
            if i == 0:
                temp = yield i
            else:
                yield i
            i+=1
    t = test()
    print(t.__next__())
    t.send("guagua") #这次temp一直保存了guagua
    
    
    # 运行结果
    0
    
  • 生成器-5-完成多任务

    def test1():#多任务当中的协程
        while True:               #分三种
            print("----1----")    #协程
            yield None            #进程
                                  #线程
    
    def test2():
        while True:
            print("----2----")
            yield None
    
    t1 = test1()
    t2 = test2()
    
    while True:
        t1.__next__()
        t2.__next__()
    
    # 运行结果
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    ----1----
    ----2----
    死循环
    
posted on 2019-05-04 19:38  gmlgxx  阅读(72)  评论(0)    收藏  举报