如何使用itertools.combinations?
itertools.combinations 是 Python 的一个非常有用的工具,用于创建一个迭代器,该迭代器返回由输入的可迭代对象中元素构成的所有长度为 r 的子序列组合,而且是按照顺序生成的,不包含重复的组合。这里的组合意味着,与元素的排列顺序无关,即 {1,2} 和 {2,1} 在组合中被视为相同的组合。
import itertools
# 定义一个可迭代对象
iterable = [1, 2, 3]
# 指定组合的长度
r = 2
# 使用 itertools.combinations 创建组合
combinations = itertools.combinations(iterable, r)
# 遍历并打印每一个组合
for combo in combinations:
print(combo)
输出:
(1, 2) (1, 3) (2, 3)
如果你想要探索不同长度的组合,可以将 itertools.combinations 放在一个循环中,并动态改变长度 r。
import itertools
X = [1, 2, 3, 4]
for i in range(len(X)):
comb = itertools.combinations(X, i+1)
for c in comb:
print(c)
(1,) (2,) (3,) (4,) (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4) (1, 2, 3) (1, 2, 4) (1, 3, 4) (2, 3, 4) (1, 2, 3, 4)
关注公众号「水沐教育科技」,在手机上阅读所有教程,随时随地都能学习。内含一款搜索神器,免费下载全网书籍和视频。

微信扫码关注公众号