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

 迭代器

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

常见的迭代器有 (列表、元祖、字典、字符串、文件 等),通常我们是使用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
>>> 

 生成器

一旦一个函数中有 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
>>> 

生成器推导式的应用.

>>> #列表推导式
>>> # 在列表中加一个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(生成器)

----------- 赠人玫瑰,手有余香     如果本文对您有所帮助,动动手指扫一扫哟   么么哒 -----------


未经作者 https://www.cnblogs.com/xin1006/ 梦相随1006 同意,不得擅自转载本文,否则后果自负
原文地址:https://www.cnblogs.com/xin1006/p/5724955.html