09-09-周二_16-00-25
This commit is contained in:
@@ -157,6 +157,30 @@ ret = g.send('hello')
|
||||
print('***',ret)
|
||||
```
|
||||
|
||||
- 生产包子的send版本
|
||||
|
||||
```python
|
||||
# produce函数,实现生成器获取包子数组,使用send()函数,指定获取的数量,比如produce.send(2),得到['包子1','包子2']
|
||||
# 反复使用send()可以获得包子序号是和前面连续的
|
||||
def produce(prefix="包子", start=1):
|
||||
cur = start
|
||||
qty = yield # 预激活用的第一个 yield(接收第一次 send 的数量)
|
||||
while True:
|
||||
if qty is None:
|
||||
qty = 1 # 如果传 None,就默认取 1 个
|
||||
if qty < 0:
|
||||
raise ValueError("数量必须是非负整数") # 主动抛出异常,直接让程序报错退出
|
||||
res = [f"{prefix}{i}" for i in range(cur, cur + qty)]
|
||||
cur += qty
|
||||
qty = yield res
|
||||
|
||||
|
||||
produce = produce()
|
||||
next(produce)
|
||||
print(produce.send(20))
|
||||
print(produce.send(10))
|
||||
```
|
||||
|
||||
## 列表推导式和生成器表达式
|
||||
|
||||
```python
|
||||
|
Reference in New Issue
Block a user