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 来指示迭代结束。

相关推荐
三目条件28 分钟前
C#将类属性保存到Ini文件方法(利用拓展方法,反射方式获取到分组名和属性名称属性值)
java·开发语言·c#
哈里谢顿30 分钟前
celery 中 app.delay 跟 app.send_task有什么区别
python
程序员二黑33 分钟前
元素定位翻车现场!避开这3个坑效率翻倍(附定位神器)
python·测试
RoundLet_Y35 分钟前
【知识图谱】Neo4j桌面版运行不起来怎么办?Neo4j Desktop无法打开!
数据库·python·知识图谱·neo4j
stanleychan8738 分钟前
干掉反爬!2025年最全 Python 爬虫反检测实战指南(含代码+案例)
python
stanleychan8739 分钟前
从零到一:2025年最新Python爬虫代理池搭建指南
python
Mr数据杨1 小时前
【Dv3Admin】菜单管理集成阿里巴巴自定义矢量图标库
python·django
WhereIsHero1 小时前
我的开发日志:随机数小程序
python
曲幽1 小时前
Python使用diffusers加载文生图模型教程
python·ai·prompt·pipeline·torch·image·diffusers·transforms
阿虎儿1 小时前
Python中re对象的使用方法
python