-5
給定一組k
項(例如,{1,2,3}
,對於k=3
),如何使用原始組的值生成所有可能的長度爲n
的組?應該有k**n
這樣的列表。如何從k個項目列表中生成所有n大小的集合?
給定一組k
項(例如,{1,2,3}
,對於k=3
),如何使用原始組的值生成所有可能的長度爲n
的組?應該有k**n
這樣的列表。如何從k個項目列表中生成所有n大小的集合?
可以使用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)]
我有問題了類似的解釋。但是'list(permutations(s,3))'返回'6'列表,但@OP需要返回'k^n'列表'(27)'。 – shash678