# python生成式
###### tags: `Python`
在python語法中有個很有趣的寫法
### 建立一個串列(List)內含整數型態(Int)1~9
```python=
[x for x in range(9999999)]
```
這寫法就像是合併了以下常見作法
但卻又一行程式及完成
```python=
t = []
for v in range(9999999):
t.append(v)
print(t)
```
這寫法在python中命名為`Generator Expression`
其實不知道中文講法該叫什麼姑且稱他為`生成表達式`吧
### "This made the function easier to write and much more clear than an approach using instance variables"
---
還有一東西叫Generator
中文給它取名為`生程式`,寫法如下
```python=
def reverse(data):
for i in range(len(data)-1, -1, -1):
yield data[i]
```
使用函式會返還`生成物件`
```python=
print((reverse("apple")))
```
這樣的使用方式並不正確,應該要
```python=
r = reverse("apple")
for ch in r:
print(ch)
```
yield就像是return一樣但差別在於next()一次才返還一次值
這生成式就像是遞迴函式一樣
在呼叫一次試看看
```python=
for ch in r:
print(ch)
```
理所當然無法得到任何值,因為它不再執行
### 也可以搭配Generator Expression使用
```python=
[x for x in reverse("apple")]
```
[參考](https://docs.python.org/3/tutorial/classes.html#generators)