Python中next函数如何使用

2023-05-18,

今天就跟大家聊聊有关Python中next函数如何使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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

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

class CharBufReader(object):  def __init__(self, mfile, bufSize = 1000):  self.mfile = mfile  #self.bufSize = 64 * 1024 #64k buf size  self.capacity = bufSize self.buf = '' #buf of char  self.cur = len(self.buf)  self.size = len(self.buf)  def __iter__(self):  return self  def next(self):  if self.cur == self.size:  #if self.cur == len(self.buf):  #if self.cur == self.buf.__len__():  selfself.buf = self.mfile.read(self.capacity)  self.size = len(self.buf)  if self.size == 0:  raise StopIteration  self.cur = 0 self.cur += 1  return self.buf[self.cur - 1]   class Compressor():  def caculateFrequence(self):  """The first time of reading the input file and caculate each  character frequence store in self.dict  """  self.infile.seek(0)  reader = compressor.CharBufReader(self.infile)  for c in reader:  if c in self.dict:  self.dict[c] += 1  else:  self.dict[c] = 0

看完上述内容,你们对Python中next函数如何使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注本站行业资讯频道,感谢大家的支持。

《Python中next函数如何使用.doc》

下载本文的Word格式文档,以方便收藏与打印。