转自:https://blog.csdn.net/specter11235/article/details/71189486
一、笛卡尔积:itertools.product(*iterables[, repeat])
直接对自身进行笛卡尔积:
import itertools
for i in itertools.product(‘ABCD‘, repeat = 2):
print (‘‘.join(i),end=‘ ‘)
输出结果:
AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
print (”.join(i))这个语句可以让结果直接排列到一起
end=’ ‘可以让默认的输出后换行变为一个空格
两个元组进行笛卡尔积:
import itertools
a = (1, 2, 3)
b = (‘A‘, ‘B‘, ‘C‘)
c = itertools.product(a,b)
for i in c:
print(i,end=‘ ‘)
输出结果:
(1, ‘A’) (1, ‘B’) (1, ‘C’) (2, ‘A’) (2, ‘B’) (2, ‘C’) (3, ‘A’) (3, ‘B’) (3, ‘C’)
二、排列:itertools.permutations(iterable[, r])
import itertools
for i in itertools.permutations(‘ABCD‘, 2):
print (‘‘.join(i),end=‘ ‘)
输出结果:
AB AC AD BA BC BD CA CB CD DA DB DC
三、组合:itertools.combinations(iterable, r)
import itertools
for i in itertools.combinations(‘ABCD‘, 3):
print (‘‘.join(i))
输出结果:
ABC
ABD
ACD
BCD
四、组合(包含自身重复):itertools.combinations_with_replacement(iterable, r)
import itertools
for i in itertools.combinations_with_replacement(‘ABCD‘, 3):
print (‘‘.join(i),end=‘ ‘)
输出结果:
AAA AAB AAC AAD ABB ABC ABD ACC ACD ADD BBB BBC BBD BCC BCD BDD CCC CCD CDD DDD
原文地址:https://www.cnblogs.com/eternal1025/p/9523534.html
时间: 2024-10-08 20:49:03