itertools模块通过惰性求值和C级优化提供高效迭代,其核心函数如count、cycle、chain、groupby、product等,可实现内存友好且高性能的循环操作,适用于处理大数据、组合排列及序列连接等场景。

说起Python里高效的循环迭代,
itertools
itertools
以下是一些
itertools
无限迭代器:
count(start=0, step=1)
start
step
import itertools
# 从10开始,每次加2的序列
for i in itertools.count(10, 2):
if i > 20:
break
print(i) # 输出:10, 12, 14, 16, 18, 20cycle(iterable)
for item in itertools.cycle(['A', 'B', 'C']):
print(item)
# 为了避免无限循环,这里需要一个终止条件
if item == 'C':
break # 输出:A, B, Crepeat(object, times=None)
times
times
None
for i in itertools.repeat('Hello', 3):
print(i) # 输出:Hello, Hello, Hello组合迭代器:
chain(*iterables)
for x in itertools.chain([1, 2], (3, 4), 'abc'):
print(x, end=' ') # 输出:1 2 3 4 a b czip_longest(*iterables, fillvalue=None)
zip
for item in itertools.zip_longest([1, 2], ['a', 'b', 'c'], fillvalue='-'):
print(item)
# 输出:(1, 'a'), (2, 'b'), ('-', 'c')排列组合迭代器:
product(*iterables, repeat=1)
repeat
# 两个列表的笛卡尔积
for p in itertools.product('AB', 'CD'):
print(''.join(p), end=' ') # 输出:AC AD BC BD
print()
# 重复自身两次的笛卡尔积 (等同于 product('ABC', 'ABC'))
for p in itertools.product('ABC', repeat=2):
print(''.join(p), end=' ') # 输出:AA AB AC BA BB BC CA CB CCpermutations(iterable, r=None)
iterable
r
r
iterable
for p in itertools.permutations('ABC', 2):
print(''.join(p), end=' ') # 输出:AB AC BA BC CA CBcombinations(iterable, r)
iterable
r
for c in itertools.combinations('ABC', 2):
print(''.join(c), end=' ') # 输出:AB AC BCcombinations_with_replacement(iterable, r)
iterable
r
for c in itertools.combinations_with_replacement('ABC', 2):
print(''.join(c), end=' ') # 输出:AA AB AC BB BC CC过滤与切片迭代器:
islice(iterable, stop)
islice(iterable, start, stop[, step])
iterable
# 从无限序列中取前5个
for i in itertools.islice(itertools.count(), 5):
print(i, end=' ') # 输出:0 1 2 3 4
print()
# 从10开始,取到20,步长为3
for i in itertools.islice(itertools.count(10), 0, 11, 3):
print(i, end=' ') # 输出:10 13 16 19takewhile(predicate, iterable)
iterable
predicate
False
data = [1, 2, 3, 4, 1, 5, 6]
for x in itertools.takewhile(lambda x: x < 4, data):
print(x, end=' ') # 输出:1 2 3dropwhile(predicate, iterable)
iterable
predicate
False
data = [1, 2, 3, 4, 1, 5, 6]
for x in itertools.dropwhile(lambda x: x < 4, data):
print(x, end=' ') # 输出:4 1 5 6filterfalse(predicate, iterable)
predicate
False
data = [1, 2, 3, 4, 5, 6]
for x in itertools.filterfalse(lambda x: x % 2 == 0, data):
print(x, end=' ') # 输出:1 3 5分组迭代器:
groupby(iterable, key=None)
key
key
None
things = [('animal', 'bear'), ('animal', 'duck'), ('plant', 'cactus'), ('vehicle', 'speed boat'), ('vehicle', 'bus')]
# 必须先排序
things.sort(key=lambda x: x[0])
for key, group in itertools.groupby(things, lambda x: x[0]):
print(f"{key}: {list(group)}")
# 输出:
# animal: [('animal', 'bear'), ('animal', 'duck')]
# plant: [('plant', 'cactus')]
# vehicle: [('vehicle', 'speed boat'), ('vehicle', 'bus')]这问题问得好,很多人初次接触
itertools
list(permutations(my_large_list))
itertools
这不仅节省了宝贵的内存,对于处理海量数据或无限序列时几乎是唯一的选择,而且由于很多
itertools
模块里函数不少,但有些真的是‘明星产品’,用起来特别顺手,能解决很多实际问题:
product
product
list(itertools.product(['红', '蓝'], ['S', 'M', 'L'], ['棉', '麻']))
combinations
combinations
['age', 'gender', 'income', 'city']
list(itertools.combinations(features, 2))
groupby
groupby
logs = [{'user': 'A', 'action': 'login'}, {'user': 'A', 'action': 'view'}, {'user': 'B', 'action': 'logout'}]logs.sort(key=lambda x: x['user'])
for k, g in itertools.groupby(logs, key=lambda x: x['user']): print(k, list(g))
chain
chain
for x in itertools.chain(user_data_from_db, user_data_from_cache, user_data_from_file): process(x)
这个问题其实跟第一个有点像,但我们更聚焦于具体的对比。最直观的例子就是处理大规模数据。
[x for x in range(10**7)]
itertools.count()
itertools
itertools
itertools
itertools.permutations
for i in range(10)
itertools.count(0)
itertools
以上就是如何使用itertools模块进行高效的循环迭代?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号