# python itertools模块实现排列组合

### 一、你会怎么写？

``````#!/usr/bin/env python
# code from www.361way.com
import string
basestring = string.ascii_lowercase + string.digits
for s1 in string.ascii_lowercase:
for s2 in basestring:
print (s1 + s2)
``````

### 二、笛卡尔积：itertools.product(*iterables[, repeat])

``````import itertools
for i in itertools.product('ABCD', repeat = 2):
print (''.join(i),end=' ')
``````

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=' ')
``````

### 三、排列：itertools.permutations(iterable[, r])

``````import itertools
for i in itertools.permutations('ABCD', 2):
print (''.join(i),end=' ')
``````

### 四、组合：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=' ')
``````