'''列表迭代的本质:__iter()__函数返回一个迭代器,然后可以调用迭代器上的next方法''' arr = [1,2,3,4,5] arr_iterator = arr.__iter__() print(arr_iterator.__next__()) print(next(arr_iterator))
'''一个典型的迭代器实现。例子来自《流畅的python》.''' import re import reprlib RE_WORD = re.compile('w+') class Sentence: def __init__(self,text): self.text = text self.words = RE_WORD.findall(text) def __repr__(self): return 'Sentence(%s)' %reprlib.repr(self.text) def __iter__(self): return SentenceIterator(self.words) class SentenceIterator: def __init__(self,words): self.words = words self.index = 0 def __next__(self): try: word = self.words[self.index] except IndexError: raise StopIteration() self.index += 1 return word def __iter__(self): return self s = Sentence('abDdd a dd dw') for i in s: print(i)
'''用生成器创建的迭代对象。''' def frange(start, stop, increment): x = start while x < stop: yield x x += increment for i in frange(0,5,0.5): print(i)
'''用生成器实现费波切纳算法''' import sys def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print(next(f), end=" ") except StopIteration: sys.exit()