迭代器是一個實現迭代器協議的容器對象。它基於next()
和__iter__()
兩個方法。
class IterDemo(object):
def __init__(self, stop):
self.start = 0
self.stop = stop
def next(self):
if self.start == self.stop:
raise StopIteration
self.start += 1
return self.start
def __iter__(self):
return self
>>> from iter_demo import IterDemo
>>> type(IterDemo(10))
<class 'iter_demo.IterDemo'>
>>> print [val for val in IterDemo(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
生成器是一個返回生成迭代器的方法。generator iterator
A function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.
一個返回生成迭代器的方法。它看起來像一個正常的方法,但是它包含一個yield
表達式使得它能夠在for循環中實時生產出一個可以用的值,並且也可以通過next()
方法在此次迭代中接收值。
Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.
通常是提及的生成器方法,很多情況下就是提及的生成迭代器。在上下文不是很明顯的情況下使用完成的表述能避免歧義。
>>> def fibonacci():
... a, b = 0, 1
... while True:
... yield b
... a, b = b, a + b
...
>>> fibonacci()
<generator object fibonacci at 0xb7352d74>
生成器中的方法:
next()
:返回容器的下一個項目send()
:可以將一個值傳入容器中並返回下一個項目throw()
:允許客戶端傳入要拋出的類型異常close()
:拋出一個GeneratorExit
異常協同程序是可以掛起、恢復,並且有多個進入點的函數。
列表推導
>>> [val for val in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
生成器表達式 genexp
>>> (val for val in range(10))
<generator object <genexpr> at 0xb7352d74>
>>> [x for x in (val for val in range(10))]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
itertools模塊
islice:窗口迭代器
>>> import itertools
>>> input_val = 'a,b,c,d,e,f,g,h,i,j,k'
>>> def starting_return(num):
... for x in itertools.islice(input_val.split(','), num, None):
... yield x
...
>>> starting_return(2)
<generator object starting_return at 0xb71e9054>
>>> [val for val in starting_return(2)]
['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
>>> [val for val in starting_return(5)]
['f', 'g', 'h', 'i', 'j', 'k']
>>> [val for val in starting_return(0)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
tee:往返式迭代器
......