示例工程 17-generators-coroutines
17-generators-coroutines/05-infinite-stream/infinite_stream.py
"""演示无限生成器与 islice 取前 N 项。"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from itertools import cycle, islice
def take[T](values: Iterable[T], count: int) -> list[T]:
return list(islice(values, count))
def counter(start: int = 0) -> Iterator[int]:
while True:
yield start
start += 1
def main() -> None:
colors = cycle(["r", "g", "b"])
print(f"first 7: {take(colors, 7)}")
print(f"next two: {take(colors, 2)}")
print(f"counter: {take(counter(10), 5)}")
if __name__ == "__main__":
main()