itertools
是 Python 标准库中的一个模块,提供了针对迭代器的高效循环操作工具。它特别适用于处理大型数据集或需要生成复杂序列的情况,因为它的函数返回的是迭代器而不是列表,从而节省内存。
这些函数生成无限长度的迭代器。
itertools.count(start=0, step=1)
:
从 start
开始,每次递增 step
。
pythonimport itertools
for i in itertools.count(10, 2):
print(i)
if i >= 20:
break
# 输出: 10, 12, 14, 16, 18, 20
itertools.cycle(iterable)
:
无限重复给定的可迭代对象。
pythonimport itertools
count = 0
for item in itertools.cycle(['a', 'b', 'c']):
print(item)
count += 1
if count >= 6:
break
# 输出: a, b, c, a, b, c
itertools.repeat(object[, times])
:
重复指定的对象,可以选择重复次数。
pythonimport itertools
for i in itertools.repeat('hello', 3):
print(i)
# 输出: hello, hello, hello
这些函数用于生成各种组合和排列。
itertools.product(*iterables, repeat=1)
:
计算多个输入的笛卡尔积。
pythonimport itertools
for p in itertools.product([1, 2], ['a', 'b']):
print(p)
# 输出: (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')
itertools.permutations(iterable, r=None)
:
返回长度为 r
的所有排列。
pythonimport itertools
for p in itertools.permutations('abc', 2):
print(''.join(p))
# 输出: ab, ac, ba, bc, ca, cb
itertools.combinations(iterable, r)
:
返回长度为 r
的所有组合(不考虑顺序)。
pythonimport itertools
for c in itertools.combinations('abc', 2):
print(''.join(c))
# 输出: ab, ac, bc
itertools.combinations_with_replacement(iterable, r)
:
返回长度为 r
的所有组合(允许重复元素)。
pythonimport itertools
for c in itertools.combinations_with_replacement('abc', 2):
print(''.join(c))
# 输出: aa, ab, ac, bb, bc, cc
这些函数用于合并或分割迭代器。
itertools.chain(*iterables)
:
将多个可迭代对象连接成一个长的迭代器。
pythonimport itertools
for item in itertools.chain([1, 2, 3], ['a', 'b', 'c']):
print(item)
# 输出: 1, 2, 3, a, b, c
itertools.compress(data, selectors)
:
使用布尔选择器过滤数据。
pythonimport itertools
data = 'ABCDEFG'
selectors = [True, False, True, False, True, False, True]
for item in itertools.compress(data, selectors):
print(item)
# 输出: A, C, E, G
itertools.islice(iterable, start, stop[, step])
:
类似于切片操作,但返回的是迭代器。
pythonimport itertools
for item in itertools.islice(range(10), 2, 8, 2):
print(item)
# 输出: 2, 4, 6
这些函数用于对迭代器进行分组或筛选。
itertools.groupby(iterable, key=None)
:
根据键函数将相邻的相同元素分组。
pythonimport itertools
data = [{'key': 'a'}, {'key': 'a'}, {'key': 'b'}, {'key': 'b'}, {'key': 'a'}]
for k, g in itertools.groupby(data, key=lambda x: x['key']):
print(k, list(g))
# 输出:
# a [{'key': 'a'}, {'key': 'a'}]
# b [{'key': 'b'}, {'key': 'b'}]
# a [{'key': 'a'}]
itertools.filterfalse(predicate, iterable)
:
过滤掉使谓词为真的元素。
pythonimport itertools
for item in itertools.filterfalse(lambda x: x % 2 == 0, range(10)):
print(item)
# 输出: 1, 3, 5, 7, 9
itertools.takewhile(predicate, iterable)
:
返回满足谓词的所有初始元素,直到第一个不满足为止。
pythonimport itertools
for item in itertools.takewhile(lambda x: x < 5, [1, 4, 6, 4, 1]):
print(item)
# 输出: 1, 4
itertools.dropwhile(predicate, iterable)
:
跳过满足谓词的所有初始元素,然后返回剩余的元素。
pythonimport itertools
for item in itertools.dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1]):
print(item)
# 输出: 6, 4, 1
假设我们有一个任务,需要找出两个列表的所有可能组合,并计算每个组合的乘积:
pythonimport itertools
list1 = [1, 2, 3]
list2 = [4, 5]
for combination in itertools.product(list1, list2):
product = combination[0] * combination[1]
print(f"Combination {combination} has product {product}")
# 输出:
# Combination (1, 4) has product 4
# Combination (1, 5) has product 5
# Combination (2, 4) has product 8
# Combination (2, 5) has product 10
# Combination (3, 4) has product 12
# Combination (3, 5) has product 15