python迭代器的使用方法实例
时间:2022-03-16 18:00:09
什么是迭代器?
迭代器是带有next方法的简单对象,当然也要实现__iter__函数。迭代器能在一序列的值上进行迭代,当没有可供迭代时,next方法就会引发StopIteration 的异常。python中有很多的对象都是迭代器,例如:列表,元素,字符串,文件,映射,集合
如何使用迭代器?
1. for 变量 in 可迭代对象
list1 = [1,2,3,4,5]
for ele in list1:
print ele,
结果为:1 2 3 4 5
2. if 变量 in 可迭代对象
list1 = [1,2,3,4,5]
var = 1
if var in list1:
print 'yes!'
else:
print 'No'
3. 变量 = iter(可迭代对象)
it = iter([1,2,3,4])
print it.next()
print it.next()
print it.next()
结果为:
1
2
3
最后,总结一下:迭代器就是一对象
标签:python,迭代器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python链表的基础概念和基础用法详解
2021-02-26 07:13:50
![](https://img.aspxhome.com/file/2023/5/80435_0s.jpg)
PHP根据IP判断地区名信息的示例代码
2023-09-10 14:05:55
利用python做数据拟合详情
2023-04-22 15:32:17
![](https://img.aspxhome.com/file/2023/1/103221_0s.png)
微信小程序实现星星评价效果
2023-08-24 10:04:45
![](https://img.aspxhome.com/file/2023/0/56140_0s.gif)
python使用jieba实现中文分词去停用词方法示例
2021-02-04 11:27:17
Python with用法实例
2022-09-07 19:34:05
Python编程入门指南之函数
2021-05-13 15:45:31
LINUX下Oracle数据库用户创建方法详解
2023-07-22 02:02:20
利用Python编写个冷笑话生成器
2021-05-10 15:13:20
![](https://img.aspxhome.com/file/2023/1/112521_0s.jpg)
11个Python3字典内置方法大全与示例汇总
2021-11-26 22:33:51
![](https://img.aspxhome.com/file/2023/2/99472_0s.jpg)
python通过http下载文件的方法详解
2021-11-11 04:26:23
Python实现打乒乓小游戏
2023-07-20 04:48:53
![](https://img.aspxhome.com/file/2023/1/105391_0s.gif)
运行asp.net程序 报错:磁盘空间不足
2011-11-03 17:16:22
眼未动,心已动【碳酸饮料会】
2009-09-01 19:32:00
![](https://img.aspxhome.com/file/UploadPic/20099/1/t1qlbxxobrxxxxxxxx-455-221-73s.jpg)
Python进度条的制作代码实例
2022-01-01 23:17:34
Python制作简单的网页爬虫
2022-10-09 12:49:16
详解duck typing鸭子类型程序设计与Python的实现示例
2022-12-26 07:12:19
Python实现读取及写入csv文件的方法示例
2021-12-29 16:41:31
![](https://img.aspxhome.com/file/2023/8/65528_0s.png)
基于Python编写一个刷题练习系统
2022-10-01 13:28:34
![](https://img.aspxhome.com/file/2023/2/79442_0s.png)
python实现任意位置文件分割的实例
2021-01-17 18:18:22