# Python 生成器
> 原文: [https://thepythonguru.com/python-generators/](https://thepythonguru.com/python-generators/)
* * *
于 2020 年 1 月 7 日更新
* * *
生成器是用于創建迭代器的函數,因此可以在`for`循環中使用它。
## 創建生成器
* * *
生成器的定義類似于函數,但只有一個區別,我們使用`yield`關鍵字返回用于`for`循環的每次迭代的值。 讓我們看一個示例,其中我們試圖克隆 python 的內置`range()`函數。
```py
def my_range(start, stop, step = 1):
? ? if stop <= start:
? ? ? ? raise RuntimeError("start must be smaller than stop")
? ? i = start
? ? while i < stop:
? ? ? ? yield i
? ? i += step
try:
? ? for k in my_range(10, 50, 3):
? ? ? ? print(k)
except RuntimeError as ex:
? ? print(ex)
except:
? ? print("Unknown error occurred")
```
**預期輸出**:
```py
10
13
16
19
22
25
28
31
34
37
40
43
46
49
```
```py
def my_range(start, stop, step = 1):
if stop <= start:
raise RuntimeError("start must be smaller than stop")
i = start
while i < stop:
yield i
i += step
try:
for k in my_range(10, 50, 3):
print(k)
except RuntimeError as ex:
print(ex)
except:
print("Unknown error occurred")
```
`my_range()`的工作方式如下:
在`for`循環中,調用`my_range()`函數,它將初始化三個參數(`start`,`stop`和`step`)的值,并檢查`stop`是否小于或等于`start`。 `i`被分配了`start`的值。 此時,`i`為`10`,因此`while`條件的值為`True`,而`while`循環開始執行。 在下一個語句`yield`中,將控制轉移到`for`循環,并將`i`的當前值分配給變量`k`,在`for`循環打印語句中執行該語句,然后該控件再次傳遞到函數`my_range()`內的第 7 行 `i`遞增。 此過程一直重復進行,直到`i < stop`為止。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象