Python迭代器定义与简单用法分析
作者:Tom文星 时间:2022-10-24 02:44:29
本文实例讲述了Python迭代器定义与简单用法。分享给大家供大家参考,具体如下:
一、什么是迭代器
迭代,顾名思义就是重复做一些事很多次(就现在循环中做的那样)。迭代器是实现了__next__()方法的对象(这个方法在调用时不需要任何参数),它是访问可迭代序列的一种方式,通常其从序列的第一个元素开始访问,直到所有的元素都被访问才结束。 [注意]:迭代器只能前进不能后退
[迭代器的优点]:
使用迭代器不要求事先准备好整个迭代过程中的所有元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后元素可以不存在或者被销毁。因此迭代器适合遍历一些数量巨大甚至无限的序列。
二、创建迭代器
A、使用内建的工厂函数iter(iterable)可以将可迭代序列转换为迭代器
a=[1,2,3,4]
b=(1,2,3)
str='Tomwenxing'
print(iter(a))
print(iter(b))
print(iter(str))
运行结果:
<listiterator object at 0x0000000001D6D550>
<tupleiterator object at 0x0000000001D6D550>
<iterator object at 0x0000000001D6D550>
B、自定义迭代器
•Python中迭代器的本质上每次调用__next__()
方法都返回下一个元素或抛出StopIteration的容器对象
•由于Python中没有“迭代器”这个类,因此具有以下两个特性的类都可以称为“迭代器”类:
1、有__next__()
方法,返回容器的下一个元素或抛出StopIteration异常
2、有__iter__()
方法,返回迭代器本身
#斐波那契数列
class Fabs():
def __init__(self,max):
self.max=max
self.n,self.a,self.b=0,0,1
def __iter__(self):#定义__iter__方法
return self
def __next__(self):#定义__next__方法
if self.n<self.max:
tmp=self.b
self.a,self.b=self.b,self.a+self.b
#等价于:
#t=(self.a,self.a+self.b)
#self.a=t[0]
#self.b=t[1]
self.n+=1
return tmp
raise StopIteration
print(Fabs(5))
for item in Fabs(10):
print(item,end=' ')
运行结果:
<__main__.Fabs object at 0x00000000023F9278>
1 1 2 3 5 8 13 21 34 55
三、迭代器的方法
1.iter.__next__():返回迭代器的下一个元素,但没有下一个元素时抛出StopIteration异常
list=[1,2,3,4]
list=iter(list)
print(list.__next__())
print(list.__next__())
print(list.__next__())
print(list.__next__())
print(list.__next__())
运行结果:
Traceback (most recent call last):
File "E:\py3Demo\Hello\iterDemo.py", line 7, in <module>
print(list.__next__())
StopIteration
1
2
3
4
2.iter.__iter__():返回迭代器对象本身
list=[1,2,3,4]
list=iter(list)
print(list.__iter__())
运行结果:
<list_iterator object at 0x0000000001D6F208>
希望本文所述对大家Python程序设计有所帮助。
来源:https://www.cnblogs.com/duwenxing/p/7397759.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
安装多个版本的TensorFlow的方法步骤
![](https://img.aspxhome.com/file/2023/3/93473_0s.png)
centos 安装python3.6环境并配置虚拟环境的详细教程
python的构建工具setup.py的方法使用示例
![](https://img.aspxhome.com/file/2023/1/95581_0s.png)
Go语言通过Luhn算法验证信用卡卡号是否有效的方法
Python爬虫:通过关键字爬取百度图片
![](https://img.aspxhome.com/file/2023/9/70019_0s.png)
新云4.0 模板通用标签说明
vue封装一个弹幕组件详解
SQL Server 使用 SET FMTONLY ON 获得表的元数据
![](https://img.aspxhome.com/file/2023/3/106273_0s.jpg)
对YOLOv3模型调用时候的python接口详解
![](https://img.aspxhome.com/file/2023/3/93513_0s.jpg)
用python的哈希函数对密码加密
![](https://img.aspxhome.com/file/2023/8/99138_0s.png)
Flask框架踩坑之ajax跨域请求实现
![](https://img.aspxhome.com/file/2023/3/80703_0s.png)
python绘制动态曲线教程
![](https://img.aspxhome.com/file/2023/4/134464_0s.jpg)
浅谈Python数学建模之线性规划
![](https://img.aspxhome.com/file/2023/5/82885_0s.png)
如何在Win下mysql备份恢复命令
SqlServer存储过程实现及拼接sql的注意点
ACCESS的参数化查询 附ASP和C#(ASP.NET)函数
thinkphp5.1 框架钩子和行为用法实例分析
Python图形绘制操作之正弦曲线实现方法分析
![](https://img.aspxhome.com/file/2023/3/60513_0s.png)
Vue中父组件向子组件通信的方法
Python数据可视化详解
![](https://img.aspxhome.com/file/2023/8/78498_0s.jpg)