Python next函数实际操作教程


Python next函数在实际使用的时候有不少的问题需要我们学习。相关的技术需要不断学习才能更好的掌握。下面就向大家介绍下有关于Python next函数的具体使用情况。

下面给出一个用iterator的实现,一个CharBufReader类,封装了buf,对外提供一次读取一个byte的接口(内部实现从buf读取,buf读完再fill buf)。这样代码好复用。

因为提供Python next函数,所以可以用iterator访问。但是效率上很慢,和以前不优化,用file.read(1)差不多90s左右的时间。可以看出就是主要是因为函数调用造成了原来程序速度慢。而不是因为不用自己写的缓冲读文件时间长。

  1. class CharBufReader(object):  
  2. def __init__(self, mfile, bufSize = 1000):  
  3. self.mfile = mfile  
  4. #self.bufSize = 64 * 1024 #64k buf size  
  5. self.capacity = bufSize 
  6. self.buf = '' #buf of char  
  7. self.cur = len(self.buf)  
  8. self.size = len(self.buf)  
  9. def __iter__(self):  
  10. return self  
  11. def next(self):  
  12. if self.cur == self.size:  
  13. #if self.cur == len(self.buf):  
  14. #if self.cur == self.buf.__len__():  
  15. selfself.buf = self.mfile.read(self.capacity)  
  16. self.size = len(self.buf)  
  17. if self.size == 0:  
  18. raise StopIteration  
  19. self.cur = 0 
  20. self.cur += 1  
  21. return self.buf[self.cur - 1]   
  22. class Compressor():  
  23. def caculateFrequence(self):  
  24. """The first time of reading the input file and caculate each  
  25. character frequence store in self.dict  
  26. """  
  27. self.infile.seek(0)  
  28. reader = compressor.CharBufReader(self.infile)  
  29. for c in reader:  
  30. if c in self.dict:  
  31. self.dict[c] += 1  
  32. else:  
  33. self.dict[c] = 0 

以上就是对Python next函数的详细介绍,希望大家有所收获。

相关内容

    暂无相关文章

评论关闭