Python中實現排列組合,從M個元素中有序或者無序選取N個元素的集合

Python中實現排列組合,從M個元素中有序或者無序選取N個元素的集合。

import itertools

'''
無序排列
combinations(M個數的集合,選取N個數爲一組)
'''
c = list(itertools.combinations([1, 2, 3, 4], 2))
print(c)

'''
有序排列
permutations(M個數的集合,選取N個數爲一組)
'''
p = list(itertools.permutations([1, 2, 3, 4], 2))
print(p)

'''
測試結果:
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
'''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章