全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 7 分钟 ✍️ juanwangdev

Python 无限迭代器

itertools 模块提供三个无限迭代器:countcyclerepeat,可生成永不停止的迭代序列。

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

无限迭代器永不耗尽,必须用 islicetakewhile 或配合有限序列使用。

要点总结

迭代器用法示例
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

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python yield from 语法
下一篇 → Python 生成器函数
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库