给定一组k
项(例如,{1,2,3}
,k=3
),如何使用原始集的值生成所有可能的长度n
集合?应该有k**n
个此类列表。
答案 0 :(得分: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)]
<强> 更新: 强> 也许这更像是被要求的:
>>> 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)]