python排列组合之itertools模块

1. 参考

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

9.7. itertools — Functions creating iterators for efficient looping

2. 代码

 1 # 有序排列permutations A。
 2 # 不放回抽球两次,r参数默认为len('abc')
 3 >>> for i in itertools.permutations('abc',2):
 4 ...  print(i)
 5 ...
 6 ('a', 'b')
 7 ('a', 'c')
 8 ('b', 'a')
 9 ('b', 'c')
10 ('c', 'a')
11 ('c', 'b')
12 # 无序组合combinations C。
13 # 不放回抽球两次,r必选
14 >>> for i in itertools.combinations('abc',2):
15 ...  print(i)
16 ...
17 ('a', 'b')
18 ('a', 'c')
19 ('b', 'c')
20 
21 
22 
23 # 笛卡尔积
24 # 放回抽球,默认repeat=1
25 # product(A, B) returns the same as:  ((x,y) for x in A for y in B).
26 # repeat=2相当于for i in itertools.product('abc','abc')
27 >>> for i in itertools.product('abc',repeat=2):
28 ...  print(i)
29 ...
30 ('a', 'a')
31 ('a', 'b')
32 ('a', 'c')
33 ('b', 'a')
34 ('b', 'b')
35 ('b', 'c')
36 ('c', 'a')
37 ('c', 'b')
38 ('c', 'c')
39 # 放回抽球,r必选,相当于product再去掉非自定义字典序'CBA'顺序的
40 >>> for i in itertools.combinations_with_replacement('CBA', 2):
41 ...  print(i)
42 ...
43 ('C', 'C')
44 ('C', 'B')
45 ('C', 'A')
46 ('B', 'B')
47 ('B', 'A')
48 ('A', 'A')

 

posted @ 2017-06-23 09:56  my8100  阅读(1722)  评论(0编辑  收藏  举报