import itertools a = ('1% purchase', '1%-2% purchase', '2%-3% purchase','3%-5% purchase','5%-10% Purchase') b = ('1% add to cart', '1%-2% add to cart', '3%-5% add to cart','3%-5% add to cart','5%-10% add to cart') c = ('1% checkout','1%-2% checkout','2%-3% checkout','3%-5% checkout','5%-10% checkout') d = xxxxxx for i in d: print(i,end=' ')
本文实例讲述了Python使用itertools模块实现排列组合功能。分享给大家供大家参考,具体如下:
一、笛卡尔积:itertools.product(*iterables[, repeat])
直接对自身进行笛卡尔积:
1
2
3
|
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=' '
可以让默认的输出后换行变为一个空格
两个元组进行笛卡尔积:
1
2
3
4
5
6
|
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])
1
2
3
|
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)
1
2
3
|
import itertools for i in itertools.combinations( 'ABCD' , 3 ): print (''.join(i)) |
输出结果:
ABC
ABD
ACD
BCD
四、组合(包含自身重复):itertools.combinations_with_replacement(iterable, r)
1
2
3
|
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