0. Python中引入itertools
1. 笛卡尔积:
product(iter1, iter2,...,iterN,[repeat=i])
from itertools import product #笛卡尔积
#3种常见的iter类型
for x in product('',repeat=3):
print(x)
for x in product([1,0],repeat=3):
print(x)
for x in product((0,1),repeat=3):
print(x)
结果
('', '', '')
('', '', '')
('', '', '')
('', '', '')
('', '', '')
('', '', '')
('', '', '')
('', '', '') (1, 1, 1)
(1, 1, 0)
(1, 0, 1)
(1, 0, 0)
(0, 1, 1)
(0, 1, 0)
(0, 0, 1)
(0, 0, 0) (0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
复杂示例
lucky+=[int(''.join([str(y) for y in x])) for x in list(product([4,7],repeat=i))]
2.全排列
permutations(iterable,[,r])
from itertools import permutations for x in permutations('ABC'):
print(x)
结果
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')
3. 组合
combinations(iterable, r)
from itertools import combinations for x in combinations('ABCD',):
print(x)
for x in combinations([,,,],):
print(x)
结果
('A', 'B')
('A', 'C')
('B', 'C')
(, )
(, )
(, )
未完待续...