13、Python中的迭代器

迭代器是一个数据流对象或容器,当使用其中的数据时,每次从一个数据流中取一个数据,直到数据被取完,而且数据不会被重复使用;


1、自定义迭代器

实现自定义迭代器需要实现如下的方法:

  • __iter__(): 方法返回对象本身,它是for语句使用迭代器的要求;
  • __next()__: 方法返回用于容器中下一个元素或数据。当容器中的数据用尽时引发StopIteration异常

自定义异常示例:

#依次遍历X的n次方,知道大于100时结束迭代
class MyIterator:
    def __init__(self, x=2, max=100):
        self.__x = x
        self.__mul = x
        self.__max = max

    # 定义iter函数,返回自身
    def __iter__(self):
        return self

    # 定义next函数,制定迭代器的返回值
    def __next__(self):
        if self.__x != 0 and self.__x != 1:
            self.__mul *= self.__x
            if self.__mul <= self.__max:
                return self.__mul
            else:
                raise StopIteration
        else:
            raise StopIteration

if __name__ == '__main__':
    myItor = MyIterator()
    for i in myItor:
        print(i)

运行结果:
4
8
16
32
64

迭代器类一定要在某个条件下引发StopIteration错误,以结束遍历循环,否则产生死循环。


2、内置迭代工具

(1)、内建迭代函数iter()

  • iter(iterable) , 参数为可迭代类型,如各种序列等;
  • iter(callable, sentinel),第一个参数为可调用类型,一般为函数;第二个参数称为“哨兵”,即当第一个参数调用返回值等于第二个参数的值时,迭代或遍历停止;

内建函数iter()示例:

def function():
    global x
    x += 2
    return x

if __name__ == '__main__':
    lst = [1, 2, 3, 4]
    for i in iter(lst):             #iter()函数一个参数
        print(i, end=' ')
    print()
    x = 0
    for i in iter(function, 12):    #iter()函数两个参数
        print(i, end=' ')

运行结果:
1 2 3 4
2 4 6 8 10


(2)、itertools模块中常见的迭代工具

itertools模块中常见的迭代工具,如下表所示:

分类 函数名称 描述
无限迭代 count(start[, step]) 从start开始,以step为步长计数迭代
无限迭代 cycle(seq) 无限循环迭代seq
无限迭代 repeat(elem[, n]) 循环迭代elem
迭代短序列 chain(p, q, …) 链接迭代,将p,q…连结起来迭代,就像从一个序列中迭代
迭代短序列 compress(data, selectors) 依据selectors中的值选择迭代data序列中的值
迭代短序列 dropwhile(pred, seq) 当pred对序列元素处理结果为假时开始迭代seq后的值
迭代短序列 filterfalse(pred, seq) 当pred处理为假的元素
迭代短序列 takewhile(pred, seq) 与dropwhile相反
迭代短序列 tee(it, n) 将it重复n次进行迭代
组合迭代序列 product(p, q, …[, n]) 迭代排列出所有的序列
组合迭代序列 permutations(p, r) 迭代序列中r个元素的排列
组合迭代序列 combinations(p, r) 迭代序列中r个元素的组合

猜你喜欢

转载自blog.csdn.net/douzhq/article/details/79342546