Python 的 异步生成器

等级 5448 次按键

这把两个异步生成器(含yield的async def)串联起来:一个生成数字,另一个进行过滤,再用'async for'取出偶数。

Python 代码

# import asyncio 用于 async/await 支持
1import asyncio
2
# 含yield的async def使async_range成为异步生成器
3async def async_range(start: int, stop: int, delay: float = 0.1):
# 像普通range()一样从start循环到stop-1
4 for i in range(start, stop):
# await asyncio.sleep 模拟异步延迟
5 await asyncio.sleep(delay)
# yield 异步地一次生成一个值
6 yield i
7
# async def async_filter 过滤异步可迭代对象
8async def async_filter(predicate, async_iterable):
# async for 迭代异步生成器
9 async for item in async_iterable:
# 只生成通过谓词的项
10 if predicate(item):
# 生成匹配的项
11 yield item
12
# async def main 是主协程
13async def main():
# results 列表收集过滤后的值
14 results = []
# 取出async_range(1, 10)中过滤后的偶数
15 async for num in async_filter(lambda x: x % 2 == 0, async_range(1, 10, 0.01)):
# 将每个偶数添加到 results
16 results.append(num)
# 打印收集的偶数
17 print(f"Even numbers: {results}")
18
# asyncio.run 启动事件循环并运行 main
19asyncio.run(main())

运行结果

Even numbers: [2, 4, 6, 8]
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • :× 12
  • (× 12
  • )× 12
  • ,× 7
  • _× 6
  • .× 5
  • =× 4
  • "× 2
  • [× 1
  • ]× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习