Python--迭代器

1.迭代器Iterator
是可迭代对象的一个子集
可迭代:list,dict,strings

2.生成器Generator
生成一个迭代器的工具,生成器是函数或者表达式

3.利用迭代器处理fibonacci

def fib2():
    a,b=0,1
    while True:
        yield a
        a,b=b,a+b

#需要先实例化一个对象,然后调用对象的next方法
[a.next() for i in xrange(10)]

利用迭代器,就是避免每一次获取x的结果,都要把x-1的结果都算一遍

4.send用法
send(msg)与next()的区别在于send可以传递参数给yield表达式,这时传递的参数会作为yield表达式的值,而yield的参数是返回给调用者的值。初始调用时必须先next()或send(None),否则会报错。

def f():
    x=''
    while True:
        x+=yield 'yield'
        print(x)

a=f()
a.next()
while True:
    a.send(raw_input('input sth\n'))

==>

input sth
a
a
input sth
b
ab
input sth
c
abc
input sth
d
abcd
input sth

5.内置模块itertools

itertools.permutations(List)
将List所有可能性作为一个迭代器返回

itertools.product(List1,List2)
itertools.repeat(List,times)
itertools.chain(iterator1,iterator2,iterator3...)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值