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

相关推荐
吴佳浩6 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
feiduoge6 小时前
教程 44 - 相机系统
windows·游戏引擎·图形渲染
长安第一美人6 小时前
C 语言可变参数(...)实战:从 logger_print 到通用日志函数
c语言·开发语言·嵌入式硬件·日志·工业应用开发
Larry_Yanan6 小时前
Qt多进程(一)进程间通信概括
开发语言·c++·qt·学习
superman超哥7 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
不爱吃糖的程序媛7 小时前
Ascend C开发工具包(asc-devkit)技术解读
c语言·开发语言
bu_shuo7 小时前
MATLAB奔溃记录
开发语言·matlab
Learner__Q7 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
————A7 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
你的冰西瓜7 小时前
C++标准模板库(STL)全面解析
开发语言·c++·stl