python 實現排列組合


對於一個數組(或任何可以迭代的元素集),可以通過itertools包中的permutationscombinations輕松完成排列,組合

python3中permutationscombinations返回的是一個迭代器,可以通過list轉化為一個列表,方便我們進一步處理

具體用法看下面的例子

import itertools
from itertools import permutations, combinations

print("Permutations of 'bar'")
print(list(permutations('bar')))

#輸出結果
#Permutations of 'bar'
#[('b', 'a', 'r'), ('b', 'r', 'a'), ('a', 'b', 'r'), ('a', 'r', 'b'), ('r', 'b', 'a'), ('r', 'a', 'b')]

print("Combinations of 2 letters from 'bar'")
print(list(combinations('bar', 2)))

#輸出結果
#Combinations of 2 letters from 'bar'
#[('b', 'a'), ('b', 'r'), ('a', 'r')]


免責聲明!

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



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