itertools.combinations(iterable, r)
是 Python 中 itertools 模块中的一个函数。它用于生成给定可迭代对象(比如列表、元组等)中,长度为 r 的所有可能组合
iterable
:一个可迭代对象,比如列表或元组,其中包含将要生成组合的元素。r
:生成组合中元素的数量。
import itertools
# 定义一个可迭代对象
numbers = [1, 2, 3, 4]
# 生成长度为 2 的所有组合
combinations = list(itertools.combinations(numbers, 2))
# 打印结果
print(combinations)
# 输出
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]