Python-迭代

1、迭代器

迭代器是一个对象,它可以记录遍历的相关信息,迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器有两个基本的方法:iter() 和 next()。我们都过命令行工具,了解一下python的底层迭代机制

python 复制代码
>>> items = [1,2,3]
>>> it = iter(items)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

上面执行的流程

  • 根据给定的可迭代对象生成迭代器
  • 从迭代器中重复获取下一项
  • 如果成功获得了下一项,上一项已经消失
  • 如果在获取下一项时遇到"StopIteration"异常,则停止循环,因为后面没有其他项了

2、应用

1、不使用for循环实现对可迭代对象便利,可以使用什么实现遍历呢?

手动的遍历可迭代对象,使用 next() 函数并在代码中捕获 StopIteration 异常

python 复制代码
def manual_iter():
    with open('test.txt') as f:
        try:
            while True:
                line = next(f)
                print(line, end='')
        except StopIteration:
            pass

2、自定义迭代器

Python 中创建自定义迭代器,需要实现一个类,该类必须包含 iter () 和 next () 方法。iter () 方法返回迭代器对象本身,next() 方法返回序列中的下一个元素

python 复制代码
class EvenIterator:
    def __init__(self, lst):
        self.lst = lst
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.index < len(self.lst):
            current = self.lst[self.index]
            self.index += 1
            if current % 2 == 0:
                return current
        raise StopIteration

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in EvenIterator(my_list):
    print(i)

输出:
2
4
6
8
10

在上面的示例中定义了一个名为 EvenIterator 的类,该类接受一个列表作为参数。我们实现了 iter () 和 next () 方法来定义迭代器的行为,并在 next() 方法中使用 raise StopIteration 来指示迭代结束。

相关推荐
Warson_L2 小时前
高性能架构设计
python·go
databook2 小时前
新数据到手,先跑哪几步检查
python·数据分析
czq_26867194873 小时前
Python打卡第46天
开发语言·python
Flynt4 小时前
日涨4000星的OSINT工具,我拿Linus的用户名和一个随机字符串实测了一遍
python·安全
2601_967987375 小时前
安装 Redis 或 Redis Stack
linux·windows·redis·macos·安装
Evand J5 小时前
【MATLAB例程介绍】(17)永磁同步电机(PMSM)基于自适应无迹卡尔曼滤波(AUKF)的电流噪声在线估计。测量噪声协方差自适应与转速估计对比仿真
开发语言·matlab·卡尔曼滤波·无迹卡尔曼滤波·pmsm·电机滤波
BaiPeter6 小时前
ZPL文件预览
开发语言·c++
曲径海盗7 小时前
【Python 学习第 53 天】列表基础
python·学习笔记·编程入门
Dumbness7 小时前
群里 @ 机器人发"查订单",指令一条都没命中:微信群机器人在路由前漏掉的几步归一化
python·微信
用户1614840955457 小时前
用 M4 Pro 跑羽毛球视频 AI 分析(二):TrackNet MPS 加速 3.2 倍、卡尔曼滤波补漏与自动回合剪辑
python