Python:迭代器 Iterator

 

  迭代在不少語言中都有存在,在c++中,你們更加推崇使用迭代而不是下標的方式來訪問數據,下面咱們來看看python中的迭代。python

  python中咱們能夠使用迭代來遍歷list,dirc,甚至file,讓咱們先來以最簡單的方式來認識下迭代:c++

list = [1,2,3]
for i in list:  #彷佛和c++的  for(auto iter:vec){}很像 dosomething

  在c++中咱們能夠對iterator進行加減操做,來移動迭代器,那python中是如何實現的呢?查閱python 文檔:函數

能夠看到,python 中有iterators,Reverse Iteration 和 Copyable Iterators性能

  那麼先來看看iterators:this

  iter()是實現迭代的很重要的函數,它用來調用類中的__iter__()函數來得到一個迭代器。spa

對迭代器,咱們能夠使用for,或next()來使用它。是否有其餘函數呢?例如獲取當前指向的元素?前一個元素?code

答:沒有,確實,在咱們實際使用過程當中,幾乎沒人會使用next(),或是其餘獲取元素的函數,絕大多數是用for來遍歷。(文檔中甚至用'ugly'來形容__next__(),python真的簡潔~~)對象

    iter() 的兩種用法:iter(obj),iter(callable, sentinel)blog

   讓咱們拿一個list 來試一下,iter()將list轉爲了listiterator,一樣能夠用for來遍歷,使用過一次後,在使用next獲取下一個元素顯示StopIteration(迭代器已到最後)文檔

那咱們如何使本身定義的類來實現iterator,讓他也能夠實現用for來遍歷呢?

文檔中這樣說:

### 
Classes can define how they are iterated over by defining an
__iter__() method; this should take no additional arguments and
return a valid iterator object.  A class that wants to be an
iterator should implement two methods: a next() method that behaves
as described above, and an __iter__() method that returns self.
###

想要定義的類實現迭代須要定義__next__()和__iter__()兩個方法,__iter__()用來返回一個特殊的迭代器對象,__next__()用來完成實際的迭代。

 

最後來看下迭代器的性能:

看來迭代器性能好於下標迭代。

相關文章
相關標籤/搜索