Python迭代器和生成器(高级编程四)
迭代器
- 迭代器是一个可以记住遍历的位置的对象。
- 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
- 迭代器有两个基本的方法:iter() 和 next()。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from collections import Iterator, Iterable # Iterable 为可迭代对象 # Iterator 为迭代器 list=[1,2,3,4] it = iter(list) # 讲可迭代对象(数组)转为迭代器 print(next(it)) print(next(it)) print(next(it)) >> 1 >> 2 >> 3 |
- 把一个类作为一个迭代器使用需要在类中实现两个方法
__iter__()
与__next__()
。 __iter__()
方法返回一个特殊的迭代器对象, 这个迭代器对象实现了__next__()
方法并通过StopIteration
异常标识迭代的完成。__next__()
方法(Python 2 里是next()
)会返回下一个迭代器对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x) |
生成器
- 在 Python 中,使用了
yield
的函数被称为生成器(generator) - 生成器是一个返回迭代器的函数,只能用于迭代操作
- 在调用生成器运行的过程中,每次遇到
yield
时函数会暂停并保存当前所有的运行信息,返回yield
的值, 并在下一次执行next()
方法时从当前位置继续运行 - 调用一个生成器函数,返回的是一个迭代器对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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() |
生成器如何读取大文件
文件300G,文件比较特殊,一行 分隔符 {|}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def readlines(f,newline): buf = "" while True: while newline in buf: pos = buf.index(newline) yield buf[:pos] buf = buf[pos + len(newline):] chunk = f.read(4096*10) if not chunk: yield buf break buf += chunk with open('demo.txt') as f: for line in readlines(f, "{|}"): print(line) |
Leave a Comment