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

    生成器

    1、重点

      生成器,要生成,首先想到return

      生成器是迭代器,是可迭代对象,是生成器

      迭代器是迭代器,是可迭代对象

      可迭代对象指示可迭代对象

    2、生成器与return有何区别?

      生成器就是一个函数的内存地址,这个函数内包含有yield这个关键字

      return只能返回一次函数就彻底结束了,而yield能返回多次返回值

      yieldreturn一样能返回任意值,多个值也是以元组返回

      再循环中的yield是第一次的终点,以后每次的起点和终点,

    3yield干了哪些事?

      yield把函数变成(生成器,生成器就是)迭代器相当于yielditer()next()封装到函数内部

      用return返回只能返回一次,而yield返回多次

      函数在暂停以及继续下一次运行时的状态由yield保存

      yield有两种形式,一种是语句形式(生成器函数)就是和return差不多的,另一个是表达式形式(协程函数其实也是生成器原理)

    4、生成器理解示例

     

     1 def test():
     2     print("first")
     3     yield 1  # return 1
     4     yield 2
     5     yield 3
     6 
     7 
     8 g = test()  # g是生成器,是可迭代对象是迭代器
     9 print(g)
    10 next(g)
    11 next(g)  # next超出范围还是会报错
    12 print(next(g))  # next可以触发迭代器往下走
    13 # 运行原理如下:
    14 # print(next(g))
    15 # print(next(test())
    16 # 运行test()先print("first")然后碰到yield返回1
    17 # 然后结束运行
    18 
    19 # 用for循环输出g
    20 for i in g:  #
    21     print(i)
    22 
    23 
    24 def countdown(n):
    25     print("start")
    26     while n > 0:
    27         yield n
    28         n -= 1
    29     print("done")
    30 
    31 
    32 g = countdown(5)  # g是生成器,是可迭代对象是迭代器
    33 # 用next一步一步输出g
    34 print(next(g))
    35 print(next(g))
    36 print(next(g))
    37 print(next(g))
    38 print(next(g))
    39 print(next(g))  # 超出范围,打印done后报错StopIteration
    40 # 用for循环g
    41 for i in g:
    42     print(i)
    43 # 用while循环输出g
    44 while True:
    45     try:
    46         print(next(g))
    47     except StopIteration:
    48         break
    49         # 因为迭代器是一次性的,所以上边三种循环输出方式只能同时用一种

     

    5、利用生成器的特点实现tail -f /tmp/a.txt |grep 'error'的功能

     

     1 #/usr/bin/env python
     2 #定义阶段:定义两个生成器函数
     3 import time
     4 def tail(file_path):
     5     with open(file_path,encoding="utf8") as f:
     6         f.seek(0,2)
     7         while True:
     8             line=f.readline()
     9             if not line:
    10                 time.sleep(0.5)
    11                 continue
    12             else:
    13                 yield line
    14 def grep(pattern,target):
    15     for line in target:
    16         if pattern in line:
    17             yield line
    18 #调用阶段:得到两个生成器对象
    19 g1=tail("/tmp/a.txt")
    20 g2=grep("error",g1)
    21 #next触发执行改g2生成器函数 ,用for循环或者while循环来
    22 for i in g2:
    23     print(i)

     

     

     

     

     

     

     

  • 相关阅读:
    CodeForces 347B Fixed Points (水题)
    CodeForces 347A Difference Row (水题)
    CodeForces 346A Alice and Bob (数学最大公约数)
    CodeForces 474C Captain Marmot (数学,旋转,暴力)
    CodeForces 474B Worms (水题,二分)
    CodeForces 474A Keyboard (水题)
    压力测试学习(一)
    算法学习(一)五个常用算法概念了解
    C#语言规范
    异常System.Threading.Thread.AbortInternal
  • 原文地址:https://www.cnblogs.com/jiangshitong/p/6697075.html
Copyright © 2011-2022 走看看