迭代器
通常我们接触的迭代器 序列(列表 元组 字符串) 字典
通常使用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
时间: 2024-10-29 19:12:16