python之迭代器篇

一.迭代器

 只要对象本身有_iter_()_方法,那它就是可迭代的

执行__iter__就会生成迭代器

迭代器有__next__用于获取值

__next__超出界限了会报StopIteration异常

迭代器是一次性的, 且只能一直往前迭代

获取生成器的方法:

迭代器 = 可迭代对象.__iter__()

迭代器 = iter(可迭代对象)
 
生成器获取下一个值的方法:
迭代器.__next__()
next(迭代器)
 
获取异常
d = {'a':1, 'b':2,'c':3}
i = iter(d)
while True:
    try:
        print(next(i))
    except StopIteration:
        break

 
 
 
for中的迭代器:

  for循环中in后面的就是迭代器

  实际上对于不是迭代器的for循环会自动处理成迭代器, 且在for中自动处理异常现象

d = {'a':1, 'b':2,'c':3}

for i in d:
    print(i)
 
 
文件的迭代器:

  文件句柄本身就是一个迭代器

  迭代器既含有__next__也含有__iter__

常用数据类型与迭代器:

  可迭代对象:

    字符串, 列表, 元组, 字典, 集合, 文件

  迭代器:

    文件

  判断方法:

from collections import Iterable,Iterator

f=open('file')
#判断可迭代的
print(isinstance(f,Iterable))
#查看是否是迭代器
print(isinstance(f,Iterator))
 
二.生成器

生成器是在函数中, 修改return为yield

  效果:

    执行该函数之后, 并没有执行该函数体

    执行之后, 会返回一个生成器

    生成器调用next()函数之后, 会执行函数体到yield语句位置

    再调用next()函数之后, 会接着上次yield的位置继续执行函数体

    使用for循环调用生成会一次循环就是执行到一个yield 

    生成器是迭代器的一种

    生成器一样可能会产生StopIteration异常, 需要在执行next()语句中加入异常处理

def ger(max):

    for i in range(max):
        yield i
 
g = ger(2)
 
try:
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    print("done")
 
 
生成器的应用
模拟tail -f的效果
import time
 
def tail(file):
    with open(file, "r") as f:
        f.seek(0, 2)
        while True:
            line = f.readline().strip()
            if line:
                yield line
            else:
                time.sleep(0.3)
                continue
 
g = tail('file')
for line in g:
    print(line.strip())

 
模拟tail -f | grep的效果
import time
 
def tail(file):
    with open(file, "r") as f:
        f.seek(0, 2)
        while True:
            line = f.readline().strip()
            if line:
                yield line
            else:
                time.sleep(0.3)
                continue
 
def grep(pattern,lines):
    for line in lines:
        if pattern in line:
            yield line
 
g = tail('file')
g1 = grep('info', g)
 
for line in g1:
    print(line.strip())
 
 
三.协程函数

协程函数的定义:

    在生成器的基础上, 针对yield转换为赋值语句

  具体的表现形式如下

def eater(name):
    print(name)
    while True:
        food, soup  = yield
        print("start to eat", food, soup)
    print("done")
 
g = eater("egon")
 
next(g)
 
g.send(("咖喱鸡肉盖饭","酸梅汤"))
 

协程函数的作用:

    yield 后面继续可以添加返回值

    yield前面的内容可以通过send函数来传递参数

    参数的个数和顺序要和定义的一致, 且不能有空缺

 
原文地址:https://www.cnblogs.com/asaka/p/6700393.html