- Python進階編程:編寫更高效、優雅的Python代碼
- 劉宇宙 謝東 劉艷
- 749字
- 2021-04-30 12:39:48
4.1.7 排列組合的迭代
涉及科學計算時,做排列組合是一個很常見的操作。如對于實現迭代遍歷一個集合中元素的所有可能的排列組合的需求,我們可以使用itertools模塊中相關的函數。itertools模塊提供了3個函數解決這類問題。其中一個是itertools.permutations()函數,它可以實現接收一個集合并產生一個元組序列,每個元組由集合中所有元素的一個可能的排列組成。通過打亂集合中元素排列順序生成一個元組,代碼(comb_iter.py)示例如下:
item_list = ['a', 'b', 'c'] from itertools import permutations for p in permutations(item_list): print(f'all permutations is: {p}')
執行py文件,輸出結果如下:
all permutations is: ('a', 'b', 'c') all permutations is: ('a', 'c', 'b') all permutations is: ('b', 'a', 'c') all permutations is: ('b', 'c', 'a') all permutations is: ('c', 'a', 'b') all permutations is: ('c', 'b', 'a')
如果想得到指定長度的所有排列,可以傳遞一個可選的長度參數,代碼(comb_iter.py)示例如下:
for p in permutations(item_list, 2): print(f'permutations 2 is: {p}')
執行py文件,輸出結果如下:
permutations 2 is: ('a', 'b') permutations 2 is: ('a', 'c') permutations 2 is: ('b', 'a') permutations 2 is: ('b', 'c') permutations 2 is: ('c', 'a') permutations 2 is: ('c', 'b')
使用itertools.combinations()函數可以得到輸入集合中元素的所有的排列組合,代碼(comb_iter.py)示例如下:
from itertools import combinations for c in combinations(item_list, 3): print(f'combinations 3 is: {c}') for c in combinations(item_list, 2): print(f'combinations 2 is: {c}') for c in combinations(item_list, 1): print(f'combinations 1 is: {c}')
執行py文件,輸出結果如下:
combinations 3 is: ('a', 'b', 'c') combinations 2 is: ('a', 'b') combinations 2 is: ('a', 'c') combinations 2 is: ('b', 'c') combinations 1 is: ('a',) combinations 1 is: ('b',) combinations 1 is: ('c',)
對于combinations()函數來講,元素的順序不重要。組合('a','b')與('b','a')是一樣的(最終只會輸出其中一個)。
在計算組合的時候,一旦元素被選取就會從候選中剔除掉(比如,如果元素a已經被選取,那么接下來排列組合時就不會再考慮它了)。
函數itertools.combinations_with_replacement()允許同一個元素被選擇多次,代碼(comb_iter.py)示例如下:
from itertools import combinations_with_replacement for c in combinations_with_replacement(item_list, 3): print(f'combinations with replacement is: {c}')
執行py文件,輸出結果如下:
combinations with replacement is: ('a', 'a', 'a') combinations with replacement is: ('a', 'a', 'b') combinations with replacement is: ('a', 'a', 'c') combinations with replacement is: ('a', 'b', 'b') combinations with replacement is: ('a', 'b', 'c') combinations with replacement is: ('a', 'c', 'c') combinations with replacement is: ('b', 'b', 'b') combinations with replacement is: ('b', 'b', 'c') combinations with replacement is: ('b', 'c', 'c') combinations with replacement is: ('c', 'c', 'c')
上述示例展示的僅僅是itertools模塊的一部分功能。
盡管自己可以手動實現排列組合,但是這樣做效率低。當遇到比較復雜的迭代問題時,最好可以先選擇使用itertools模塊中的函數解決。
推薦閱讀
- HTML5 移動Web開發從入門到精通(微課精編版)
- Visual Basic程序設計(第3版):學習指導與練習
- Responsive Web Design with HTML5 and CSS3
- 數據庫系統原理及MySQL應用教程
- C語言程序設計
- Django Design Patterns and Best Practices
- iOS應用逆向工程(第2版)
- Scala謎題
- C語言程序設計
- Python數據分析從0到1
- Building Serverless Web Applications
- 工業機器人離線編程
- Ext JS 4 Plugin and Extension Development
- Python物理建模初學者指南(第2版)
- Android技術內幕(系統卷)