Python学习之迭代器类型

迭代器作为Python中比较常用的数据类型,Python的官方说明文档给出了迭代器类型的详细说明:本人使用的是Python的3.7.x版本.

原文以及解释

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.


Python支持利用容器来实现迭代功能,该功能是用两个方法来实现的,这两个方法允许用户自定义的类支持迭代器。


The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

方法1,iterator.iter()

Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.


方法返回迭代器本身,允许容器和迭代器配合 for … in 语句一起使用


方法2,iterator.next()

Return the next item from the container. If there are no further items, raise the StopIteration exception.


返回容器的下一个项,如果容器元素项已经访问完成,抛出StopIteration exception


迭代器使用实例

python 迭代器脚本

class IterList():
    def __init__(self):
        self.index = 0
        self._text = [123, 456, 789, 963, "Nick", "Roly"]
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index > len(self._text) - 1:
            raise StopIteration
        self.index += 1
        return self._text[self.index-1]

if __name__ == "__main__":
setuter =  IterList()
for it in setuter:
    print(it)

运行后生成结果

迭代器实例运行结果图

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值