一 迭代器的相关概念
1 >>> for i in "FishC": 2 ... print(i) 3 ... 4 F 5 i 6 s 7 h 8 C
例子中字符串就是一个容器,同时也是一个迭代器;for语句的作用就是触发这个迭代器的迭代功能,每次从容器里面一次拿出一个数据就是迭代操作。
语法:next(iterable[, default])
参数说明:
1 >>> next(it) 2 Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4 StopIteration 5 >>> string = "FishC" 6 >>> it = iter(string) 7 >>> next(it) 8 ‘F‘ 9 >>> while True: 10 ... try: 11 ... each = next(it) 12 ... except StopIteration: 13 ... break 14 ... print(each) 15 ... 16 i 17 s 18 h 19 C 20 >>>
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 >>> fibs = Fibs() 12 >>> for each in fibs: 13 ... if each < 20: 14 ... print(each) 15 ... else: 16 ... break 17 ... 18 1 19 1 20 2 21 3 22 5 23 8 24 13
1 >>> class Fibs: 2 ... def __init__(self,n = 10): 3 ... self.a = 0 4 ... self.b = 1 5 ... self.n = n 6 ... def __iter__(self): 7 ... return self 8 ... def __next__(self): 9 ... self.a,self.b = self.b,self.a+self.b 10 ... if self.a > self.n: 11 ... raise StopIteration 12 ... return self.a 13 ... 14 >>> fibs = Fibs() 15 >>> for each in fibs: 16 ... print(each) 17 ... 18 1 19 1 20 2 21 3 22 5 23 8 24 >>> fibs = Fibs(100) 25 >>> for each in fibs: 26 ... print(each) 27 ... 28 1 29 1 30 2 31 3 32 5 33 8 34 13 35 21 36 34 37 55 38 89 39 >>>
原文:https://www.cnblogs.com/luoxun/p/13721967.html