迭代的意思类似于循环,每一次重复的过程被称为一次迭代的过程,而每一次迭代得到的结果会被用来作为下一次迭代的初始值。提供迭代方法的容器称为迭代器(如序列(列表、元组、字符串)、字典等)。
对一个容器对象调用iter()就得到它的迭代器,调用next()迭代器就会返回下一个值。入托迭代器没有值可以返回了,就会抛出异常。
•iter()
–__iter__()
•next()
–__next__()
实例1:
1 >>> string = "FishC" 2 >>> it = iter(string) 3 >>> next(it) 4 'F' 5 >>> next(it) 6 'i' 7 >>> next(it) 8 's' 9 >>> next(it) 10 'h' 11 >>> next(it) 12 'C' 13 >>> next(it) 14 Traceback (most recent call last): 15 File "<pyshell#8>", line 1, in <module> 16 next(it) 17 StopIteration
一个容器如果是迭代器,那就必须实现__iter__()魔法方法,这个方法实际上就是返回迭代器本身。重点要实现的是__next__()魔法方法,因为它决定了迭代的规则。
实例2:
1 >>> class Fibs: 2 def __init__(self): 3 self.a = 0 4 self.b = 1 5 def __iter__(self): 6 return self 7 def __next__(self): 8 self.a,self.b = self.b,self.a + self.b 9 return self.a 10 11 12 >>> fibs = Fibs() 13 >>> for each in fibs: 14 if each < 20: 15 print(each) 16 else: 17 break
1
1
2
3
5
8
13
实例3:
1 >>> class Fibs: 2 def __init__(self,n =20): 3 self.a = 0 4 self.b = 1 5 self.n = n 6 def __iter__(self): 7 return self 8 9 def __next__(self): 10 self.a,self.b = self.b,self.a + self.b 11 if self.a > self.n: 12 raise StopIteration 13 return self.a 14 15 16 >>> fibs = Fibs() 17 >>> for each in fibs: 18 print(each)
1
1
2
3
5
8
13
1 >>> fibs = Fibs(10) 2 >>> for each in fibs: 3 print(each)
1
1
2
3
5
8