Python--迭代器
2015-09-01 12:19
495 查看
小结
凡是可作用于for循环的对象都是Iterable类型;凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
Python的for循环本质上就是通过不断调用next()函数实现的,例如:
for x in [1, 2, 3, 4, 5]:
pass
实际上完全等价于:
首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])循环:
while True:try:
# 获得下一个值:
x = next(it)
except StopIteration:
# 遇到StopIteration就退出循环
break
相关文章推荐
- python bug
- Python实现身份证号码解析
- python2.7学习笔记(7) ——函数式编程
- Python--生成器
- python logging 日志详细配置
- python string包——简易函数使用
- Python学习----高级特性
- python 查找指定内容的txt文件
- python编码问题
- 【转】python import的用法
- python dom解析API目录
- python实现八皇后
- python中的xml.dom的使用
- Python Unitest 源码阅读:概述
- Python uuid
- python调用Go代码
- Python计算Project Euler Problem 3
- Ubuntu Python 环境配置
- python django 数据库查询方法总结
- 【Python学习日记】 第 b1fd 一天