对python迭代器的理解

  1. 迭代器的接口
  2. 迭代器的用法
  3. 自定义迭代器
  4. 迭代器的意义

1迭代器的接口

  • 可迭代对象
    image
  • 计算对象之间的共同属性
    image
    得到可迭代对象的共同属性
    image
    上述对象都是容器类型,都有长度
    加入文件对象再次求交集
    image
    得到可迭代对象的唯一共同接口:_iter _
    image
    image
    生成了迭代器
    同样方法计算迭代器的共同属性
    得到两个接口
    image

2迭代器的用法

点击查看代码
# 构建迭代器
actions = ['点赞','投币','收藏']
actions_iterator = iter(actions)
# 多次迭代
action = next(actions_iterator)
print(action)
action = next(actions_iterator)
print(action)
action = next(actions_iterator)
print(action)
action = next(actions_iterator)
print(action)
运行结果:

image
由此总结迭代三个关键步骤:
image

通过循环模拟迭代

点击查看代码
iterator = iter(actions)
while True:
    try:
        print(next(iterator))
    except StopIteration:
        print('迭代结束')
        break
点击查看代码
Black_List = ['白嫖','取关']
class SuIterator:
    def __init__(self,actions):
        self.actions = actions
        self.index = 0 #初始化索引下标
    def __next__(self):
        while self.index < len(self.actions):
            action = self.actions[self.index]
            self.index += 1 #更新索引下标
            if action in Black_List:
                continue
            elif '币' in action:
                return  action*2
            else:
                return action
        raise  StopIteration
actions = ['点赞', '投币', '收藏']
SuziIterator = SuIterator(actions)
while True:
    try:
        print(next(SuziIterator))
    except StopIteration:
        break

迭代器协议
image
所有迭代器的_iter_方法都只用returnn self即可

4迭代器的意义

image
迭代器就是为了让数据结构能快捷地遍历而定义的辅助对象

深层的意义

现有两种可迭代对象

  • 容器类型:
    列表、元组、字典
    只有_ iter _接口
    静态的数据
    需要额外的迭代器支持
    支持多次迭代
    image
    这种情况下只有可迭代对象在前台露脸,而迭代器是在背后使用默认方式悄悄构建没有存在感,生命周期和循环绑定

  • 迭代器类型
    文件、StringIO等
    同时实现_ iter _ 和_ next _接口
    动态的
    只能迭代一次
    image
    整个迭代过程只需要迭代器,迭代器不光是从后台走到了前台,而且让可迭代对象远离了循环,和当前循环操作解耦了,于是乎一个可迭代对象可以构建出多个不同的迭代器,一种迭代器可以应用于任意多个可迭代对象,大大增强了代码复用能力

应用场景

数据管道

image
image
image

数据生成器

image
这个迭代器不需要存储数据,StopIteration都不用管,可以无穷无尽迭代下去,数据实时产生不占用内存空间

posted @ 2023-06-14 10:40  鹿丸子  阅读(29)  评论(1)    收藏  举报