1. 程式人生 > >博眾娛樂平臺開發與python學習

博眾娛樂平臺開發與python學習

獲取 index () self fin 獲取數據 getitem rep 地方

可叠代的對象、叠代器和生成器
叠代是數據處理的基石。掃描內存中方不下的數據集時,我們要找一種惰性獲取數據項的方式,即按需一次獲取一個數據項。這就是叠代器模式。

1可叠代對象

1.1序列可以叠代的原因

解釋器需要叠代對象x時,會自動調用iter(x),內置的iter函數有以下作用:

檢查對象是否實現了iter方法,如果實現了就調用它,獲取一個叠代器。

如果沒有實現iter方法,但是實現了getitem方法,python會創建一個叠代器,嘗試按順序(從索引0開始)獲取元素

如果嘗試失敗,python拋出TypeError異常,通常會提示”C object is not iterable“,其中C是目標叠代對象

2 叠代器

2.1叠代器的接口

標準的叠代器接口有兩個方法:

next:返回下一個可用的元素,如果沒有元素了,拋出StopIteration

iter:返回self,以便在應該使用可叠代對象的地方使用叠代器,例如在for循環中

6.2.2 一個經典的叠代器

#可叠代對象和叠代器一定不能在一個對象中同時實現,一下為典型的叠代器
import re
import reprlib
?
RE_WORD = re.compile(‘\w+‘)
?
class Sentence:

def __init__(self,text):
    self.text = text
    self.words = RE_WORD.findall(text)
def __iter__(self):
    return SentenceIterator(self.words)
def __repr__(self):
    return ‘Sentence(%s)‘ % reprlib.repr(self.text)

#實現叠代器
class SentenceIterator(self,words):
def init(self,words):
self.words = words
self.index = 0
def next(self):
try:
word = self.words[self.index]
except IndexError:
raise StopIteration()
self.index += 1
return word
def iter(self):

博眾娛樂平臺開發與python學習