09-09-周二_16-00-25

This commit is contained in:
2025-09-09 16:00:26 +08:00
parent 07916c4922
commit 0e70503b1b
2 changed files with 41 additions and 0 deletions

View File

@@ -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