Python next函數(shù)實(shí)際操作教程
Python next函數(shù)在實(shí)際使用的時(shí)候有不少的問題需要我們學(xué)習(xí)。相關(guān)的技術(shù)需要不斷學(xué)習(xí)才能更好的掌握。下面就向大家介紹下有關(guān)于Python next函數(shù)的具體使用情況。
下面給出一個(gè)用iterator的實(shí)現(xiàn),一個(gè)CharBufReader類,封裝了buf,對(duì)外提供一次讀取一個(gè)byte的接口(內(nèi)部實(shí)現(xiàn)從buf讀取,buf讀完再fill buf)。這樣代碼好復(fù)用。
因?yàn)樘峁㏄ython next函數(shù),所以可以用iterator訪問。但是效率上很慢,和以前不優(yōu)化,用file.read(1)差不多90s左右的時(shí)間。可以看出就是主要是因?yàn)楹瘮?shù)調(diào)用造成了原來程序速度慢。而不是因?yàn)椴挥米约簩懙木彌_讀文件時(shí)間長。
- 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
以上就是對(duì)Python next函數(shù)的詳細(xì)介紹,希望大家有所收獲。
【編輯推薦】

















