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

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

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

 

转载于:https://www.cnblogs.com/Alex-as/p/9096738.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值