《Python Cookbook 3rd》笔记(4.9):排列组合的迭代
生活随笔
收集整理的這篇文章主要介紹了
《Python Cookbook 3rd》笔记(4.9):排列组合的迭代
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
排列組合的迭代
問題
你想迭代遍歷一個集合中元素的所有可能的排列或組合
解法
itertools 模塊提供了三個函數來解決這類問題。 其中一個是itertools.permutations() ,它接受一個集合并產生一個元組序列,每個元組由集合中所有元素的一個可能排列組成。也就是說通過打亂集合中元素排列順序生成一個元組,比如:
>>> items = ['a', 'b', 'c'] >>> from itertools import permutations >>> for p in permutations(items): ... print(p) ... ('a', 'b', 'c') ('a', 'c', 'b') ('b', 'a', 'c') ('b', 'c', 'a') ('c', 'a', 'b') ('c', 'b', 'a') >>>如果你想得到指定長度的所有排列,你可以傳遞一個可選的長度參數。就像這樣:
>>> for p in permutations(items, 2): ... print(p) ... ('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b') >>>使用 itertools.combinations() 可得到輸入集合中元素的所有的組合。比如:
>>> from itertools import combinations >>> for c in combinations(items, 3): ... print(c) ... ('a', 'b', 'c') >>> for c in combinations(items, 2): ... print(c) ... ('a', 'b') ('a', 'c') ('b', 'c') >>> for c in combinations(items, 1): ... print(c) ... ('a',) ('b',) ('c',) >>>對于 combinations() 來講,元素的順序已經不重要了。也就是說,組合 (‘a’,‘b’) 跟 (‘b’, ‘a’) 其實是一樣的 (最終只會輸出其中一個)。
在計算組合的時候,一旦元素被選取就會從候選中剔除掉(比如如果元素’a’已經被選取了,那么接下來就不會再考慮它了)。而 函數itertools.combinations_with_replacement() 允許同一個元素被選擇多次,比如:
>>> for c in combinations_with_replacement(items, 3): ... print(c) ... ('a', 'a', 'a') ('a', 'a', 'b') ('a', 'a', 'c') ('a', 'b', 'b') ('a', 'b', 'c') ('a', 'c', 'c') ('b', 'b', 'b') ('b', 'b', 'c') ('b', 'c', 'c') ('c', 'c', 'c') >>>討論
盡管你也可以自己手動實現排列組合算法,但是這樣做得要花點腦力。當我們碰到看上去有些復雜的迭代問題時,最好可以先去看看 itertools 模塊。如果這個問題很普遍,那么很有可能會在里面找到解決方案!
總結
以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(4.9):排列组合的迭代的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用Python去除扫描型PDF中的水印
- 下一篇: Python外(5)-for-enume