python 迭代器之chain

可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator

可以直接作用于for循环的对象统称为可迭代对象:Iterable

直接作用于for循环的数据类型有以下几种:

 一类是集合数据类型,如listtupledictsetstr等;

一类是generator,包括生成器和带yield的generator function。

集合数据类型如listdictstr等是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() 

  在python 3.x中 generator(有yield关键字的函数则会被识别为generator函数)中的next变为__next__了,next是python 3.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

将多个迭代器作为参数, 但只返回单个迭代器,

它产生所有参数迭代器的内容, 就好像他们是来自于一个单一的序列.

 

posted on 2018-05-27 17:53  Alex-zs  阅读(550)  评论(0编辑  收藏  举报

导航