在前面的博文中介紹過如何構造序列對象的迭代器。本文將通過生成器函數來重寫這篇博文的代碼。
事實上,一個序列對象的迭代器,依賴于一個整數序列的迭代器。看下面的代碼。
def MyGenerator(len): start = 0 while start < len: yield start start = start + 1gen = MyGenerator(3)PRint gen.next()print gen.next()print gen.next()print gen.next()當調用第1次next方法時, 會首先執行MyGenerator方法的第1行代碼start = 0。然后進入循環。這里len的值通過參數傳入為3。因此while的條件表達式為真。進入循環后,遇到yield語句,方法的執行過程被掛起。next方法的返回值為start的值,即0。當調用第2次next方法時,接著上面的掛起點,往下執行start = start + 1語句,start的值變為1。接著又進入while循環的條件判斷,start<len依然為真。因此,又執行yield語句。但是由于start值為1,故而這一次next方法返回的值為1。
第3次next方法的調用類似。
當調用第4次next方法時,while循環的條件判斷start < len為假,while循環結束,MyGenerator方法調用也隨之結束,拋出StopIteration異常。
輸出結果
012Traceback (most recent call last): File "test.py", line 21, in <module> print gen.next()StopIteration有了上面的結果,重寫序列對象的迭代器輕而易舉。def MyGenerator(sequence): start = 0 while start < len(sequence): yield sequence[start] start = start + 1gen = MyGenerator([1,2,3,'a','b','c'])for i in gen: print i對比之前迭代器類的代碼,我們可以認識到,yield關鍵字為構造迭代器提供了多大的方便。它使得代碼長度縮減許多,同時也大大增強了可讀性。
新聞熱點
疑難解答