python 迭代器之chain

來源:互聯網
上載者:User

標籤:itertools   獲得   tool   highlight   tools   target   next   cti   ack   

可以被 next()函數調用並不斷返回下一個值的對象稱為迭代器: Iterator

可以直接作用於for迴圈的對象統稱為可迭代對象:Iterable

直接作用於for迴圈的資料類型有以下幾種:

 一類是集合資料類型,如listtupledictsetstr等;

一類是generator,包括產生器和帶yield的generator function。

集合資料類型如listdictstr等是Iterable但不是Iterator,不過可以通過iter()函數獲得一個Iterator對象。

在Python中,這種一邊迴圈一邊計算的機制,稱為產生器:generator。

>>> g = (x * x for x in range(10))>>> next(g)0>>> next(g)1>>> next(g)4>>> next(g)9>>> next(g)16>>> next(g)25>>> next(g)36>>> next(g)49>>> next(g)64>>> next(g)81>>> next(g)Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration

  

yield在函數中的功能類似於return,不同的是yield每次返回結果之後函數並沒有退出,

而是每次遇到yield關鍵字後返回相應結果,並保留函數當前的運行狀態,等待下一次的調用。

def func():      for i in range(0,3):          yield i    f = func()  f.next()  f.next() 

  在python 3.x中 generator(有yield關鍵字的函數則會被識別為generator函數)中的next變為__next__了,next是python 3.x以前版本中的方法

itertools.chain(*iterables)
def chain(*iterables):    # chain(‘ABC‘, ‘DEF‘) --> A B C D E F    for it in iterables:        for element in it:            yield element

將多個迭代器作為參數, 但只返回單個迭代器,

它產生所有參數迭代器的內容, 就好像他們是來自於一個單一的序列.

 

python 迭代器之chain

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.