【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
2017-07-21 12:00
976 查看
如何使用迭代器(Iterator)
迭代可迭代对象
迭代器
# -*- coding:utf-8 -*- the_string = "AllenMoore" next(the_string)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-ed837072a8a2> in <module>() 1 2 the_string = "AllenMoore" ----> 3 next(the_string) TypeError: str object is not an iterator
# -*- coding:utf-8 -*- the_string = "AllenMoore" the_iter = iter(the_string) next(the_iter)
'A'
生成器
# -*- coding:utf-8 -*- def gen_function(): for i in range(3): yield i for item in gen_function(): print item gen = gen_function() print '\n' print next(gen) print '\n' print next(gen) print '\n' print next(gen) print '\n' print next(gen)
0 1 2 0 1 2 --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-10-c9cd08f2ec3a> in <module>() 15 print next(gen) 16 print '\n' ---> 17 print next(gen) StopIteration:
# -*- coding:utf-8 -*- def gen_fibonacci(n): a = b = 1 result = [] for i in range(n): result.append(a) a, b = b, a+b return result for x in gen_fibonacci(20): print x
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
# -*- coding:utf-8 -*- def gen_fibonacci(n): a = b = 1 for i in range(n): yield a a, b = b, a+b for x in gen_fibonacci(20): print x
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
什么是迭代器(Iterator)
迭代(Iteration):从某个对象取出一个元素的过程;使用循环来遍历某个对象;迭代器(Iterator):定义有next或者\_\_next\_\_方法的对象;遍历一个容器的对象;
可迭代对象(Iterable):定义有\_\_iter\_\_或者下标索引的\_\_getitem\_\_方法的对象;
生成器(Generator):迭代器之一;只能对其迭代一次,运行时生成值;
何时使用迭代器(Iterator)
不想同一时间将所有计算的结果集分配到内存的时候相关文章推荐
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事