例如以下程式可產生 2 到 n-1 之間的整數
1 2 3 4 5 6 7 8 9 10 11 12 13 | def fun(n): for i in range ( 2 , n): yield i for j in fun( 7 ): print (j) # 《程式語言教學誌》的範例程式 # 檔名:gen01.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

第 5 行利用 j 取得產生器函數 fun() 所產生的數字,然後在第 6 行呼叫 print() 印出。
以下程式可將字串 (string) 倒過來印出
1 2 3 4 5 6 7 8 9 10 11 12 13 | def reverse(data): for i in range ( len (data) - 1 , - 1 , - 1 ): yield data[i] for i in reverse( "wonderful" ): print (i * 33 ) # 《程式語言教學誌》的範例程式 # 檔名:gen02.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

這是利用 range() 建立一個串列 (list) ,該串列中依序儲存字串的最大索引值到最小索引值,然後用 yield 產生字元,直到倒序讀完字串。
以下程式將英文單字中母音字母以 1 替換,非母音字母以 0 替換,產生的 01 序列儲存在串列中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def t(data): for i in data: if i in "aeiou" : yield 1 if i not in "aeiou" : yield 0 s = "perpetual" d = [] for i in t(s): d.append(i) print (d) print () # 《程式語言教學誌》的範例程式 # 檔名:gen03.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

第 12 行
12 | d.append(i) |
這是利用串列的 append() 方法 (method) ,可附加任意物件 (object) 到串列裡頭,排在所有元素 (element) 的最後。
中英文術語對照 | |
---|---|
函數 | function |
數值 | value |
關鍵字 | keyword |
產生器函數 | generator function |
串列 | list |
方法 | method |
物件 | object |
元素 | element |
參考資料
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/simple_stmts.html
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/simple_stmts.html
2 則留言:
第1個範例應該是產生2(含)到7(不含)之間的整數
這部份打錯了,已修改,感謝指正 :)
張貼留言