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

Python学习笔记010_迭代器_生成器

2016-08-01 10:52 609 查看
迭代器

迭代就类似于循环,每次重复的过程被称为迭代的过程,每次迭代的结果将被用来作为下一次迭代的初始值,提供迭代方法的容器被称为迭代器。

常见的迭代器有 (列表、元祖、字典、字符串、文件 等),通常我们是使用for语句完成迭代

#使用for 迭代字典的例子:
>>> links = {"鱼C工作室":"http://www.fishc.com/",
"鱼C论坛":"http://bbc.fishc.com"}
>>> for each in links:
print("%s-->%s" %(each,links[each]));

鱼C论坛-->http://bbc.fishc.com
鱼C工作室-->http://www.fishc.com/
>>>


Python自己提供了两个BIF函数 iter() , next()

  对于一个对象使用iter()函数就得到它的迭代器对象

  调用next()迭代器就会返回下一个值

  迭代结束的标识:Python抛出一个StopIteration异常.

>>> string = "123"
>>> it = iter(string)
>>> next(it)
'1'
>>> next(it)
'2'
>>> next(it)
'3'
>>> next(it)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
next(it)
StopIteration
>>>


iter()对应的魔法方法是__iter__(), next()对应的魔法方法是__next__()

__iter__() 实际上是 return self, next()决定了迭代器的规则

>>> class Fibs:
def __init__(self,n=10):
self.a = 0
self.b = 1
self.n = n

def __iter__(self):
return self

def __next__(self):
self.a,self.b = self.b,self.a+self.b
if self.a>self.n:
raise StopIteration
return self.a

>>> fibs = Fibs()
>>> for each in fibs:
print(each)

1
1
2
3
5
8
>>> fibs = Fibs(100)
>>> for each in fibs:
print(each)

1
1
2
3
5
8
13
21
34
55
89
>>>


[b]生成器[/b]

一旦一个函数中有 yield,它就是生成器 , yield相当于return,函数遇到yield就会返回yield后面的值,函数处于暂停状态

生成器是一个特殊的迭代器

协同程序:可以运行的独立函数调用,函数可以暂停或者挂起,并在需要的时候从程序离开的地方继续或者重新开始.

>>> def MyGen():
print ("生成器被执行!")
yield 1
yield 2

>>> myG = MyGen()
>>> next(myG)
生成器被执行!
1
>>> next(myG)
2
>>> next(myG)
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
next(myG)
StopIteration
>>>


[b]生成器推导式的应用.[/b]

>>> #列表推导式
>>> # 在列表中加一个for语句
>>> a = [i for i in range(50) if not (i%2) and i%3]
>>> a
[2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32, 34, 38, 40, 44, 46]
>>>
>>> #字典推导式
>>> b = {i:i%2==0 for i in range(10)}
>>> b
{0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}
>>>
>>> # 集合推导式
>>> c = {i for i in [1,2,3,2,4,2,4,6,4,7]}
>>> c
{1, 2, 3, 4, 6, 7}
>>> #元组
>>> e = (i for i in range(10))
>>> e
<generator object <genexpr> at 0x02113030>
>>> # 这里的e就是生成器 推导式
>>> next(e)
0
>>> for each in e:
print(each)

1
2
3
4
5
6
7
8
9
>>> # 生成器推导式作为函数的参数时,不用加括号
>>> sum(i for i in range(100) if i%2)
2500
>>>


扩展阅读:解释 yield 和 Generators(生成器)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: