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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM