python3: 迭代器與生成器(1)

1. 手動遍歷迭代器

你想遍歷一個可迭代對象中的全部元素,可是卻不想使用for循環。app

>>> items = [1, 2, 3]
>>> # Get the iterator
>>> it = iter(items) # Invokes items.__iter__()
>>> # Run the iterator
>>> next(it) # Invokes it.__next__()
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
StopIteration
>>>

2. 代理迭代

3.使用生成器建立新的迭代模式

一個函數中須要有一個 yield 語句便可將其轉換爲一個生成器。 跟普通函數不一樣的是,生成器只能用於迭代操做函數

>>> def countdown(n):
...     print('Starting to count from', n)
...     while n > 0:
...         yield n
...         n -= 1
...     print('Done!')
...

>>> # Create the generator, notice no output appears
>>> c = countdown(3)
>>> c
<generator object countdown at 0x1006a0af0>

>>> # Run to first yield and emit a value
>>> next(c)
Starting to count from 3
3

>>> # Run to the next yield
>>> next(c)
2

>>> # Run to next yield
>>> next(c)
1

>>> # Run to next yield (iteration stops)
>>> next(c)
Done!
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
StopIteration
>>>

4. 實現迭代器協議

5. 反向迭代

6.帶有外部狀態的生成器函數

7.迭代器切片

函數 itertools.islice() 正好適用於在迭代器和生成器上作切片操做。好比:spa

>>> def count(n):
...     while True:
...         yield n
...         n += 1
...
>>> c = count(0)
>>> c[10:20]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable

>>> # Now using islice()
>>> import itertools
>>> for x in itertools.islice(c, 10, 20):
...     print(x)
...
10
11
12
13
14
15
16
17
18
19

8. 跳過可迭代對象的開始部分

場景:你想遍歷一個可迭代對象,可是它開始的某些元素你並不感興趣,想跳過它們。代理

>>> from itertools import dropwhile
>>> with open('/etc/passwd') as f:
...     for line in dropwhile(lambda line: line.startswith('#'), f):
...         print(line, end='')
...

若是你已經明確知道了要跳過的元素的個數的話,那麼能夠使用 itertools.islice() 來代替。code

相關文章
相關標籤/搜索