標籤:itertools 獲得 tool highlight tools target next cti ack
可以被
next()函數調用並不斷返回下一個值的對象稱為迭代器:
Iterator。
可以直接作用於for迴圈的對象統稱為可迭代對象:Iterable。
直接作用於for迴圈的資料類型有以下幾種:
一類是集合資料類型,如list、tuple、dict、set、str等;
一類是generator,包括產生器和帶yield的generator function。
集合資料類型如list、dict、str等是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