Python:迭代器 Iterator

來源:互聯網
上載者:User

標籤:reverse   call   ever   技術   遍曆   returns   methods   存在   需要   

 

  迭代在很多語言中都有存在,在c++中,大家更加推崇使用迭代而不是下標的方式來訪問資料,下面我們來看看python中的迭代。

  python中我們可以使用迭代來遍曆list,dirc,甚至file,讓我們先來以最簡單的方式來認識下迭代:

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:

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

對迭代器,我們可以使用for,或next()來使用它。是否有其他函數呢?例如擷取當前指向的元素?前一個元素?

答:沒有,確實,在我們實際使用過程中,幾乎沒人會使用next(),或是其他擷取元素的函數,絕大多數是用for來遍曆。(文檔中甚至用‘ugly‘來形容__next__(),python真的簡潔~~)

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

   讓我們拿一個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 andreturn a valid iterator object.  A class that wants to be aniterator should implement two methods: a next() method that behavesas described above, and an __iter__() method that returns self.###

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

 

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

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

Python:迭代器 Iterator

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.