您的位置:首页 > 编程语言 > Python开发

Python--迭代器

2016-01-27 15:56 435 查看
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...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: