python排列组合之itertools模块

时间:2022-03-17 05:15:03

1. 参考

几个有用的python函数 (笛卡尔积, 排列, 组合)

9.7. itertools — Functions creating iterators for efficient looping

2. 代码

 # 有序排列permutations A。
# 不放回抽球两次,r参数默认为len('abc')
>>> for i in itertools.permutations('abc',2):
... print(i)
...
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')
# 无序组合combinations C。
# 不放回抽球两次,r必选
>>> for i in itertools.combinations('abc',2):
... print(i)
...
('a', 'b')
('a', 'c')
('b', 'c') # 笛卡尔积
# 放回抽球,默认repeat=1
# product(A, B) returns the same as: ((x,y) for x in A for y in B).
# repeat=2相当于for i in itertools.product('abc','abc')
>>> for i in itertools.product('abc',repeat=2):
... print(i)
...
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')
# 放回抽球,r必选,相当于product再去掉非自定义字典序'CBA'顺序的
>>> for i in itertools.combinations_with_replacement('CBA', 2):
... print(i)
...
('C', 'C')
('C', 'B')
('C', 'A')
('B', 'B')
('B', 'A')
('A', 'A')