0%

python排列组合

python排列组合

排列

1
2
3
4
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

组合(高中学习的组合,不包含重复)

1
2
3
4
import itertools
for i in itertools.combinations('ABCD', 2):
print (''.join(i),end=' ')
>> AB AC AD BC BD CD

组合(包含自身重复)

1
2
3
4
import itertools
for i in itertools.combinations_with_replacement('ABCD', 2):
print (''.join(i),end=' ')
>> AA AB AC AD BB BC BD CC CD DD

笛卡尔积(内积)

1
2
3
4
5
6
7
8
9
10
11
12
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
# 两个不同元祖之间的笛卡尔积
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')