python 迭代器之chain,pythonchain,可以被next()函
python 迭代器之chain,pythonchain,可以被next()函
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
可以直接作用于for循环的对象统称为可迭代对象:Iterable。
直接作用于for循环的数据类型有以下几种:
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generator function。
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
在Python中,这种一边循环一边计算的机制,称为生成器:generator。
>>> g = (x * x for x in range(10))>>> next(g)0>>> next(g)1>>> next(g)4>>> next(g)9>>> next(g)16>>> next(g)25>>> next(g)36>>> next(g)49>>> next(g)64>>> next(g)81>>> next(g)Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
yield在函数中的功能类似于return,不同的是yield每次返回结果之后函数并没有退出,
而是每次遇到yield关键字后返回相应结果,并保留函数当前的运行状态,等待下一次的调用。
def func(): for i in range(0,3): yield i f = func() f.next() f.next()
在python3.x中 generator(有yield关键字的函数则会被识别为generator函数)中的next变为__next__了,next是python3.x以前版本中的方法
itertools.chain(*iterables)
def chain(*iterables): # chain(‘ABC‘, ‘DEF‘) --> A B C D E F for it in iterables: for element in it: yield element
将多个迭代器作为参数, 但只返回单个迭代器,
它产生所有参数迭代器的内容, 就好像他们是来自于一个单一的序列.
python 迭代器之chain
相关内容
- python基础-函数式编程,python基础编程,python基础-函
- python--生成器,,生成器一、概念 p
- Python标准库(1) — Itertools模块,pythonitertools, itertoo
- 高效的 itertools 模块,itertools模块, Python 内置的
- 粗谈Python内置库itertools,pythonitertools, 在这里简单拿几
- python itertools模块学习笔记,pythonitertools,python itert
- 用Python对各种编程语言进行代码高亮,python高亮,下面来
- 1_python 入门,1_python,1、python 特
- 《笔记》python itertools的groupby分组数据处理,itertoolsg
- 完美配置Python3.5+Anaconda+PyQt5,实现UI和其他模块的结合
评论关闭