DAY 18
0
Data Technology

## python iterator和generator雜談之一

``````example1.py:

mylist = [2,4,6,8,10]

for  i  in  mylist:

print(i)  # 會依序print出 2 4 6 8 10

# 這三行程式會依序迭代(也可以說是遍歷)mylist裏面的5個物件
``````

(1) _iter_：回傳一個iterator物件，而這個物件可以呼叫__next__函數。
(2) _next_：這個函數會實際執行iterator物件的迭代行為。

``````In python3 shell:
>>> mylist = [2,4,6,8,10]
>>> mylist_iterator = iter(mylist) # 這個iter()函數會調用python預設的mylist.__iter__函數，並回傳一個iterator物件，然後我們用mylist_iterator這個變數來儲存這個iterator物件
>>> # 開始迭代
>>> i = next(mylist_iterator) # i = 2 , next()函數會調用python預設的mylist_iterator.__next__函數
>>> print(i)
2
>>> i = next(mylist_iterator) # i = 4
>>> print(i)
4
>>> i = next(mylist_iterator) # i = 6
>>> print(i)
6
>>> i = next(mylist_iterator) # i = 8
>>> print(i)
8
>>> i = next(mylist_iterator) # i = 10
>>> print(i)
10
>>> i = next(mylist_iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> # 當最後一個元素遍歷完，再呼叫mylist_iterator.__next__就會跑出一個 StopIteration 的例外，一般for in在呼叫__next__的過程中遇到了 StopIteration 就會自動停止 for loop的執行
``````

http://kissg.me/2016/04/09/python-generator-yield/

30天python雜談30