說明:關於Python中迭代器的解釋
Iterator是迭代器的意思,它的作用是一次產生一個數據項,直到沒有爲止。這樣在 for 循環中就可以對它進行循環處理了。那麼它與一般的序列類型(list, tuple等)有什麼區別呢?它一次只返回一個數據項,佔用更少的內存。但它需要記住當前的狀態,以便返回下一數據項。它是一個有着next()方法的對象。而序列類型則保存了所有的數據項,它們的訪問是通過索引進行的。
舉個前面的例子來說就像readlines和xreadlines的區別,readlines是一次性讀入放入內存中,而xreadlines是每次只讀取一行放入內存中,這意味着,在讀取當前行的時候,需要有相應記數器記下當前的讀取狀態,暫時可以先這樣去理解。
1.實例1:使用next()函數來讀取迭代器中的數
·可演示如下:
>>> a = iter(range(10)) #創建一個迭代器 >>> a <listiterator object at 0x7f251917ec10> >>> a.next() 0 >>> a.next() 1 >>> a.next() 2 >>> a.next() 3 >>> a.next() 4 >>> a.next() 5 >>> a.next() 6 >>> a.next() 7 >>> a.next() 8 >>> a.next() 9 >>> a.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
·a存放的是迭代器中的地址,next()可以讀取下一個位置的元素;
·next()函數不會判斷迭代器的結束,只能根據輸出異常來判斷迭代的結束;
2.readline的簡單解釋
·文件操作也可以通過next()函數讀取每一行:
>>> f = file('student_info.txt') >>> f.next() 'stu1101 mingjia.xu [email protected] 263 SystemAdmin 18810404260\r\n' >>> f.next() 'stu1102 Yangjiansong [email protected] A8music SystemAdmin 13601247960\r\n' >>> f.next() 'stu1103 zouxinkai [email protected] jishubu systemadmin 1861214111' >>> f.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
·readline也是通過上面迭代的方式來處理文件內容,只是readline增加了異常處理的功能,因此不會報錯:
>>> f = file('student_info.txt') >>> f.readline() 'stu1101 mingjia.xu [email protected] 263 SystemAdmin 18810404260\r\n' >>> f.readline() 'stu1102 Yangjiansong [email protected] A8music SystemAdmin 13601247960\r\n' >>> f.readline() 'stu1103 zouxinkai [email protected] jishubu systemadmin 1861214111' >>> f.readline() ''
3.通過循環獲取迭代器中的內容
·演示如下:
>>> a = iter(range(10)) >>> while True: ... a.next() ... 0 1 2 3 4 5 6 7 8 9 Traceback (most recent call last): File "<stdin>", line 2, in <module> StopIteration
·只能通過類似while True循環實現;
·通過該方法可以獲取迭代器中的內容,並進一步對異常情況進行處理。