首页 > 编程语言 > 详细

Python--30 迭代器

时间:2017-09-13 21:52:31      阅读:261      评论:0      收藏:0      [点我收藏+]

迭代器

  通常我们接触的迭代器 序列(列表 元组 字符串) 字典

  通常使用for语句来进行迭代

Python提供了两个BIF

  iter()

  __iter__()

  next()

  __next__()

 

>>> for i in Junjie:
...     print(i)
... 
J
u
n
j
i
e
>>> for item in links:
...     print(%s -> %s % (item,links[item]))
... 
百度 -> www.baidu.com
谷歌 -> www.google.com
技术 -> stackoverflow
>>> string = junjie
>>> it = iter(string)
>>> next(it)
j
>>> next(it)
u
>>> next(it)
n
>>> next(it)
j
>>> next(it)
i
>>> next(it)
e
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> string = junjie
>>> it = iter(string)
>>> while True:
...     try:
...             each = next(it)
...     except StopIteration:
...             break
...     print(each)
... 
j
u
n
j
i
e
>>> for each in string:
...     print(each)
... 
j
u
n
j
i
e

 

魔法方法

>>> class Fibs:
...     def __init__(self):
...             self.a = 0
...             self.b = 1
...     def __iter__(self):
...             return self
...     def __next__(self):
...             self.a,self.b = self.b,self.a+self.b
...             return self.a
... 
>>> for each in fibs:
...     if each < 20:
...             print(each)
...     else:
...             break
... 
1
1
2
3
5
8
13

 

>>> 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

 

Python--30 迭代器

原文:http://www.cnblogs.com/fengjunjie-w/p/7517820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!