4 回答

狐的傳說
TA貢獻1804條經驗 獲得超3個贊
以下代碼僅適用于Python 2.6及更高版本
一,進口itertools:
import itertools
排列(訂單事宜):
print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
組合(順序無關緊要):
print list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
笛卡爾積(有幾個迭代):
print list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
(2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
笛卡兒積(一個可迭代的本身):
print list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

侃侃爾雅
TA貢獻1801條經驗 獲得超16個贊
def permutations(head, tail=''): if len(head) == 0: print tail else: for i in range(len(head)): permutations(head[0:i] + head[i+1:], tail+head[i])
稱為:
permutations('abc')
添加回答
舉報
0/150
提交
取消