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

相关推荐
风早爽太9 分钟前
用 ‌Render‌ 快速部署网站和常见问题解决
python·fastapi
fox_charon34 分钟前
Windows 下 CLI 参数的引号陷阱:为什么 --resume 'uuid' 会失败
windows·shell·cmd·cli·引号
现任明教教主~1 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
李航19831 小时前
给自己的图形引擎,配上了AI渲染,做设计真是太方便了
人工智能·python·计算机视觉·ai·ai编程
L@ncor1 小时前
第六章 框架开发实践 · 学习笔记(AutoGen / AgentScope / CAMEL / LangGraph)
python·框架·autogen·langgraph·agentscope
Zhou1411361 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
染指11102 小时前
128.Agent-LangChain核心组件-中间件-调用模型的时候
人工智能·windows·中间件·langchain·agent
码匠许师傅2 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
Frag0ut3 小时前
Chrome与Chromium内核浏览器在Windows 11上的新特性全景解析
前端·chrome·windows·web安全·chromium·gemini ai·playready drm