2016-12-28 42 views

回答

2

可以使用itertools模塊:

>>> from itertools import permutations 
>>> s = set((1,2,3)) 
>>> list(permutations(s)) 

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 

>>> list(permutations(s, 2)) 
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] 

UPDATE: 也許這更像是在問:

>>> from itertools import chain, combinations_with_replacement, permutations 
>>> list(set(chain.from_iterable(permutations(x) for x in combinations_with_replacement(s, 3)))) 
[(1, 3, 2), 
(1, 3, 1), 
(3, 3, 1), 
(1, 1, 1), 
(3, 3, 3), 
(2, 3, 2), 
(3, 3, 2), 
(2, 3, 3), 
(2, 3, 1), 
(3, 2, 2), 
(3, 1, 3), 
(3, 2, 3), 
(3, 1, 2), 
(1, 2, 1), 
(3, 1, 1), 
(3, 2, 1), 
(1, 2, 2), 
(1, 2, 3), 
(2, 1, 2), 
(2, 2, 3), 
(2, 1, 3), 
(2, 2, 2), 
(1, 1, 3), 
(2, 1, 1), 
(1, 1, 2), 
(2, 2, 1), 
(1, 3, 3)] 
+1

我有問題了類似的解釋。但是'list(permutations(s,3))'返回'6'列表,但@OP需要返回'k^n'列表'(27)'。 – shash678

相關問題