Python 无限迭代器
itertools 模块提供三个无限迭代器:count、cycle、repeat,可生成永不停止的迭代序列。
count:无限计数
从指定起点开始无限计数:
Python
from itertools import count, islice
# 默认从0开始,步长为1
counter = count()
print(list(islice(counter, 5))) # [0, 1, 2, 3, 4]
# 指定起点和步长
counter = count(start=10, step=2)
print(list(islice(counter, 5))) # [10, 12, 14, 16, 18]
# 负步长递减
counter = count(start=10, step=-1)
print(list(islice(counter, 5))) # [10, 9, 8, 7, 6]
# 浮点数步长
counter = count(start=0.0, step=0.5)
print(list(islice(counter, 5))) # [0.0, 0.5, 1.0, 1.5, 2.0]
实际应用:生成索引
Python
from itertools import count
# 为列表元素生成索引
data = ['a', 'b', 'c', 'd']
indexed = list(zip(count(), data))
print(indexed) # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
# 指定起始索引
indexed = list(zip(count(1), data))
print(indexed) # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
cycle:无限循环
无限重复迭代序列:
Python
from itertools import cycle, islice
# 循环列表元素
colors = cycle(['red', 'green', 'blue'])
print(list(islice(colors, 8))) # ['red', 'green', 'blue', 'red', 'green', 'blue', 'red', 'green']
# 循环字符串字符
chars = cycle('ABC')
print(list(islice(chars, 5))) # ['A', 'B', 'C', 'A', 'B']
实际应用:交替处理
Python
from itertools import cycle
# 交替执行不同操作
actions = cycle(['read', 'write', 'delete'])
tasks = ['file1', 'file2', 'file3', 'file4', 'file5']
for action, task in zip(actions, tasks):
print(f"{action}: {task}")
# 输出:
# read: file1
# write: file2
# delete: file3
# read: file4
# write: file5
轮询调度示例
Python
from itertools import cycle
servers = cycle(['server1', 'server2', 'server3'])
def round_robin(requests):
for server, request in zip(servers, requests):
print(f"发送 {request} 到 {server}")
round_robin(['req1', 'req2', 'req3', 'req4'])
# 发送 req1 到 server1
# 发送 req2 到 server2
# 发送 req3 到 server3
# 发送 req4 到 server1
repeat:无限重复
重复单个值:
Python
from itertools import repeat, islice
# 无限重复
r = repeat('hello')
print(list(islice(r, 5))) # ['hello', 'hello', 'hello', 'hello', 'hello']
# 指定重复次数(有限)
r = repeat('hello', 3)
print(list(r)) # ['hello', 'hello', 'hello']
# 重复数字
r = repeat(0, 5)
print(list(r)) # [0, 0, 0, 0, 0]
实际应用:填充序列
Python
from itertools import repeat, zip_longest
# zip_longest 默认用 None 填充
data = ['a', 'b', 'c']
result = list(zip_longest(range(5), data))
print(result) # [(0, 'a'), (1, 'b'), (2, 'c'), (3, None), (4, None)]
# 使用 repeat 自定义填充值
result = list(zip_longest(range(5), data, fillvalue='N/A'))
print(result) # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'N/A'), (4, 'N/A')]
初始化矩阵
Python
from itertools import repeat
# 创建填充矩阵
row = list(repeat(0, 5)) # [0, 0, 0, 0, 0]
matrix = [list(repeat(0, 5)) for _ in range(3)]
print(matrix) # [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
限制无限迭代器
无限迭代器必须配合限制函数使用:
Python
from itertools import count, cycle, repeat, islice, takewhile
# islice:切片取前n个
counter = count()
print(list(islice(counter, 10))) # [0, 1, 2, ..., 9]
# takewhile:条件取值
counter = count()
result = list(takewhile(lambda x: x < 5, counter))
print(result) # [0, 1, 2, 3, 4]
# zip:配合有限序列使用
colors = cycle(['R', 'G', 'B'])
data = [1, 2, 3, 4, 5]
result = list(zip(colors, data))
print(result) # [('R', 1), ('G', 2), ('B', 3), ('R', 4), ('G', 5)]
三者对比
| 迭代器 | 生成内容 | 参数 | 适用场景 |
|---|---|---|---|
count | 递增/递减序列 | start, step | 索引生成、计数 |
cycle | 循环重复序列 | iterable | 轮询调度、交替处理 |
repeat | 重复单个值 | value, times | 填充默认值 |
注意事项
Python
from itertools import count
# 错误:直接转换为列表会无限循环
# list(count()) # 内存溢出
# 正确:必须限制迭代次数
from itertools import islice
limited = list(islice(count(), 100))
无限迭代器永不耗尽,必须用
islice、takewhile或配合有限序列使用。
要点总结
| 迭代器 | 用法 | 示例 |
|---|---|---|
| count(start, step) | 无限计数 | count(10, 2) → 10, 12, 14, ... |
| cycle(iterable) | 循环重复 | cycle([1,2]) → 1, 2, 1, 2, ... |
| repeat(value, times) | 重复值 | repeat('x', 3) → 'x', 'x', 'x' |
D:\git2\jwdev\articles\PYTHON\进阶\迭代器与生成器\无限迭代器.md
📝 发现内容有误?点击此处直接编辑