1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import itertools from typing import Iterator, Generator
class Range: def __init__(self, start, stop): self.current = start self.stop = stop def __iter__(self): return self def __next__(self): if self.current >= self.stop: raise StopIteration val = self.current self.current += 1 return val
for n in Range(0, 5): print(n, end=" ") print()
def count_up(n): """yield suspends execution, saves state""" current = 0 while current < n: yield current current += 1
for n in count_up(5): print(n, end=" ") print()
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
for i, fib in enumerate(itertools.islice(fibonacci(), 10)): print(fib, end=" ") print()
def stream_tokens(prompt: str) -> Generator[str, None, None]: """模拟LLM流式输出""" words = ["Hello", " ", "world", "!"] for w in words: yield w
print("\nStream: ", end="", flush=True) for token in stream_tokens("hi"): print(token, end="", flush=True) print()
def fetch_batches(urls: list[str], batch_size=5): for i in range(0, len(urls), batch_size): batch = urls[i:i+batch_size] yield [{"url": u, "data": f"content_{j}"} for j, u in enumerate(batch)]
def process_batch(batch: list[dict]) -> Generator[dict, None, None]: for item in batch: item["processed"] = True yield item
def filter_items(items: Iterator[dict]) -> Generator[dict, None, None]: for item in items: if item["data"].startswith("content_0"): yield item
urls = [f"http://example.com/{i}" for i in range(15)] pipeline = filter_items(itertools.chain.from_iterable( process_batch(b) for b in fetch_batches(urls) )) for item in itertools.islice(pipeline, 3): print(item)
for n in itertools.chain([1,2], [3,4], [5]): print(n, end=" ") print()
data = [("cat", 1), ("dog", 2), ("cat", 3)] for key, group in itertools.groupby(sorted(data), key=lambda x: x[0]): print(f"{key}: {list(group)}")
|