如何从k个项目列表中生成所有n个大小的集合?

时间:2016-12-28 02:50:03

标签: python

给定一组k项(例如,{1,2,3}k=3),如何使用原始集的值生成所有可能的长度n集合?应该有k**n个此类列表。

1 个答案:

答案 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)]