码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记010_迭代器

时间:2016-08-01 12:06:44      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

 

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

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

 

Python学习笔记010_迭代器

标签:

原文地址:http://www.cnblogs.com/yangw/p/5724955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!