python中的排列組合問題

數列s=['a','b','c','d'],輸出所有兩兩組合:


#有序排列:

import itertools
import itertools
list1=['a','b','c','d']
#2指的是幾個元素組合
iter = itertools.combinations(list1,2)
print(list(iter))
#輸出結果:
  [[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]]


#無序排列
import itertools
list1=['a','b','c','d']
iter = itertools.permutations(list1,2)
print(list(iter))
#輸出結果:
[[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]]


#不使用內置工具實現無序排列
list1=['a','b','c','d']
list2 = []
for i in list1:
    for j in list1:
        if i != j:
            list2.append((i,j))
print(list3)
#輸出結果:
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c')]


#不使用內置工具實現有序排列
list1=['a','b','c','d']
list2 = []
for i in range(len(list1)):
    for j in range(i+1,len(list1)):
        if i != j:
            list2.append((list1[i],list1[j]))
print(list2)
#輸出結果:
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章