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

相关推荐
如竟没有火炬1 分钟前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
嵌入式小李.man14 分钟前
C++第十三篇:继承
开发语言·c++
机器瓦力18 分钟前
Trae使用:重构一个项目
python·ai编程
Bryce李小白20 分钟前
Kotlin Flow 的使用
android·开发语言·kotlin
jarreyer1 小时前
python离线包安装方法总结
开发语言·python
九江Mgx1 小时前
使用 Go + govcl 实现 Windows 资源管理器快捷方式管理器
windows·golang·govcl
李辰洋1 小时前
go tools安装
开发语言·后端·golang
wanfeng_091 小时前
go lang
开发语言·后端·golang
绛洞花主敏明1 小时前
go build -tags的其他用法
开发语言·后端·golang
ByteCraze1 小时前
秋招被问到的常见问题
开发语言·javascript·原型模式