-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