Python 生成所有组合

  • Post category:Python

生成所有组合是指在一组元素中选取若干个元素,生成所有可能的组合的方法。在Python中,可以使用itertools库中的combinations函数进行操作。以下是其使用方法的完整攻略:

导入模块

在运行Python程序前,需要先导入itertools模块。代码如下:

import itertools

根据需求生成组合

在导入itertools模块后,就可以调用其中的combinations函数生成所有组合了。要使用combinations函数,需要传入两个参数:一个是元素列表,另一个是选取的元素个数。代码如下:

elements = ['a', 'b', 'c', 'd']
combinations = itertools.combinations(elements, 2)

以上代码表示从元素列表中选取2个元素进行组合。

输出结果

生成的结果是一个可迭代对象,可以通过遍历来查看所有的组合,代码如下:

for combination in combinations:
    print(combination)

以上代码将输出元素列表中所有的2个元素组成的组合。

示例1:生成各种长度的字符串组合

代码如下:

import itertools

# 使用itertools生成长度为1~3的字符串的所有组合
for l in range(1, 4):
    for combination in itertools.combinations('abcdefg', l):
        print(''.join(combination))

以上代码将输出所有长度为1~3的字符串的组合,输出如下:

a
b
c
d
e
f
g
ab
ac
ad
ae
af
ag
bc
bd
be
bf
bg
cd
ce
cf
cg
de
df
dg
ef
eg
fg
abc
abd
abe
abf
abg
acd
ace
acf
acg
ade
adf
adg
aef
aeg
afg
bcd
bce
bcf
bcg
bde
bdf
bdg
bef
beg
bfg
cde
cdf
cdg
cef
ceg
cfg
def
deg
dfg
efg
abcd
abce
abcf
abcg
abde
abdf
abdg
abef
abeg
abfg
acde
acdf
acdg
acef
aceg
acfg
adef
adeg
adfg
aefg
bcde
bcdf
bcdg
bcef
bceg
bcfg
bdef
bdeg
bdfg
befg
cdef
cdeg
cdfg
cefg
defg
abcde
abcdf
abcdg
abcef
abceg
abcfg
abdef
abdeg
abdfg
abefg
acdef
acdeg
acdfg
acefg
adefg
bcdef
bcdeg
bcdfg
bcefg
bdefg
cdefg
abcdef
abcdefg

示例2:生成所有骰子点数之和为6的组合

代码如下:

import itertools

dice = [1, 2, 3, 4, 5, 6]

# 从骰子中选取所有和为6的组合
combs = []
for i in range(1, 7):
    for comb in itertools.combinations_with_replacement(dice, i):
        if sum(comb) == 6:
            combs.append(comb)

# 输出所有和为6的组合
for comb in combs:
    print(comb)

以上代码将输出所有骰子点数之和为6的组合,输出如下:

(1, 1, 1, 1, 1, 1)
(1, 1, 1, 1, 2)
(1, 1, 1, 2, 1)
(1, 1, 1, 3)
(1, 1, 2, 1, 1)
(1, 1, 2, 2)
(1, 1, 3, 1)
(1, 1, 4)
(1, 2, 1, 1, 1)
(1, 2, 1, 2)
(1, 2, 2, 1)
(1, 2, 3)
(1, 3, 1, 1)
(1, 3, 2)
(1, 4, 1)
(1, 5)
(2, 1, 1, 1, 1)
(2, 1, 1, 2)
(2, 1, 2, 1)
(2, 1, 3)
(2, 2, 1, 1)
(2, 2, 2)
(2, 3, 1)
(3, 1, 1, 1)
(3, 1, 2)
(3, 2, 1)
(4, 1, 1)
(5, 1)
(6,)