推荐答案
// www.javascriptcn.com code example
import itertools
# 1. 无限迭代器
# 使用 itertools.count() 生成无限递增的整数序列
counter = itertools.count(start=10, step=2)
for i in range(5):
print(next(counter)) # 输出: 10, 12, 14, 16, 18
# 2. 有限迭代器
# 使用 itertools.islice() 对无限迭代器进行切片
sliced_counter = itertools.islice(counter, 5)
print(list(sliced_counter)) # 输出: [20, 22, 24, 26, 28]
# 3. 组合迭代器
# 使用 itertools.combinations() 生成组合
combinations = itertools.combinations('ABCD', 2)
print(list(combinations)) # 输出: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
# 4. 排列迭代器
# 使用 itertools.permutations() 生成排列
permutations = itertools.permutations('ABC', 2)
print(list(permutations)) # 输出: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
# 5. 笛卡尔积
# 使用 itertools.product() 生成笛卡尔积
product = itertools.product('AB', '12')
print(list(product)) # 输出: [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
# 6. 分组迭代器
# 使用 itertools.groupby() 对数据进行分组
data = sorted([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
grouped_data = itertools.groupby(data)
for key, group in grouped_data:
print(f"Key: {key}, Group: {list(group)}")
# 输出:
# Key: 1, Group: [1]
# Key: 2, Group: [2, 2]
# Key: 3, Group: [3, 3, 3]
# Key: 4, Group: [4, 4, 4, 4]本题详细解读
1. 无限迭代器
itertools.count(start=0, step=1) 生成一个无限递增的整数序列,从 start 开始,每次增加 step。可以通过 next() 函数逐个获取值。
2. 有限迭代器
itertools.islice(iterable, start, stop[, step]) 用于对无限迭代器进行切片操作,返回一个有限长度的迭代器。start 和 stop 分别表示切片的起始和结束位置,step 表示步长。
3. 组合迭代器
itertools.combinations(iterable, r) 生成从 iterable 中选取 r 个元素的所有组合,组合中的元素顺序不重要。
4. 排列迭代器
itertools.permutations(iterable, r) 生成从 iterable 中选取 r 个元素的所有排列,排列中的元素顺序重要。
5. 笛卡尔积
itertools.product(*iterables, repeat=1) 生成多个可迭代对象的笛卡尔积。repeat 参数用于指定每个可迭代对象的重复次数。
6. 分组迭代器
itertools.groupby(iterable, key=None) 对 iterable 中的连续相同元素进行分组。key 是一个函数,用于指定分组依据。注意,groupby 要求输入数据已经排序。
通过 itertools 模块,可以高效地处理各种迭代器操作,避免内存浪费并提高代码的可读性。