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