概述
迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。迭代器只能往前不會后退。
延遲計算或惰性求值 (Lazy evaluation)
迭代器不要求你事先準備好整個迭代過程中所有的元素。僅僅是在迭代至某個元素時才計算該元素,而在這之前或之后,元素可以不存在或者被銷毀。這個特點使得它特別適合用于遍歷一些巨大的或是無限的集合。
今天創建了一個實體類,大致如下:
1
2
3
4
5
6
7
8
9
10
|
class Account(): def __init__( self , account_name, account_type, account_cost, return_amount = 0 ): self .account_name = account_name # 賬戶名 self .account_type = account_type # 賬戶類型 self .account_cost = account_cost # 月結費用 self .return_amount = return_amount # 返還金額 |
然后創建一個實體列表:
1
2
3
4
5
|
accounts = [Account( "張三" , "年費用戶" , 450.00 , 50 ), Account( "李四" , "月結用戶" , 100.00 ), Account( "楊不悔" , "月結用戶" , 190.00 , 25 ), Account( "任我行" , "月結用戶" , 70.00 , 10 ), Account( "凌未風" , "年費用戶" , 400.00 , 40 )] |
我想要執行next()
功能,也就是需要的時候“next”一下,得到List中的下一個元素。
直接測試一下:
結果發現List不支持next()
特性。這時候,List只是一個iterable,而不是iterator。
iterable和iterator的區別如下:
- iterable —— 只實現了__iter__的對象;
- iterator —— 同時實現了__iter__和__next__方法的對象。
其中, __iter__
返回iterator對象, __next__
則返回迭代過程的下一個元素。
1. 讓列表成為iterator
要讓前面的accounts List成為iterator只需簡單的一個iter()
函數:
1
2
|
accounts_iterator = iter (accounts) ( next (accounts_iterator)).account_name |
結果如下圖所示:
這么簡單的函數,估計還是有不少Python開發者不知道吧?
2. 自定義iterator對象
擴展開來講,如何定義自己的iterator對象呢?其實也就是按照上面的定義,實現__iter__
和__next__
方法。
我們接下來定義一個AccountIterator類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class AccountIterator(): def __init__( self , accounts): self .accounts = accounts # 賬戶集合 self .index = 0 def __iter__( self ): return self def __next__( self ): if self .index > = len ( self .accounts): raise StopIteration( "到頭了..." ) else : self .index + = 1 return self .accounts[ self .index - 1 ] |
運行結果如:
通過這一陣折騰,next()功能就實現了。Python有不少意外的功能,還等著我們不斷去探究,也許這就是Python的魅力及極客之處。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家學習或者使用python能帶來一定的幫助,如果有疑問大家可以留言交流。
原文鏈接:http://www.2gua.info/post/64