迭代器Iterator

本文深入探讨了Python中的迭代器与生成器概念,解释了如何使用next方法及for循环进行迭代,同时介绍了如何通过iter()将可迭代对象转换为迭代器。文章还提供了自定义迭代器的实例,展示了如何利用生成器函数简化迭代器的创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:
https://www.programiz.com/python-programming/iterator
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143178254193589df9c612d2449618ea460e7a672a366000

  • 一个迭代器是可以用next方法调用的。也可以用__next__()
    也可用for循环。
    实际for循环的使用,是先转为迭代器的。

  • generator,包括生成器(括号形式的列表生产式,)、带yield的generator function.

  • list,tuple,dict,str等是可迭代对象,要转换为迭代器,需要用 iter()

  • 构建自己的 迭代器,要实现__iter()__、__next()__以及StopIteration等:

### 似乎用 **generator function**会简单很多!!!

class PowTwo:
    """Class to implement an iterator
    of powers of two"""

    def __init__(self, max = 0):
        self.max = max

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration
 ------------------
 >>> a = PowTwo(4)
>>> i = iter(a)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
4
>>> next(i)
8
>>> next(i)
16
>>> next(i)
Traceback (most recent call last):
...
StopIteration
-------------------------------------------------------
>>> for i in PowTwo(5):
...     print(i)
...     
1
2
4
8
16
32
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值