我有一组值,想创建包含 2 个元素的所有子集的列表。
例如,源集 ([1,2,3])
具有以下 2 元素子集:
set([1,2]), set([1,3]), set([2,3])
有没有办法在 python 中做到这一点?
最佳答案
好像你想要itertools.combinations
:
>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]
如果你想要集合,你必须明确地转换它们。如果您不介意使用可迭代对象而不是列表,并且您使用的是 Python 3,则可以使用 map
:
>>> s = set((1, 2, 3))
>>> map(set, itertools.combinations(s, 2))
<map object at 0x10cdc26d8>
要一次查看所有结果,您可以将map
的输出传递给list
。 (在 Python 2 中,map
的输出自动是一个列表。)
>>> list(map(set, itertools.combinations(s, 2)))
[{1, 2}, {1, 3}, {2, 3}]
但是,如果您知道自己需要一个列表,那么列表理解会稍微好一些 (h/t Jacob Bowyer ):
>>> [set(i) for i in itertools.combinations(s, 2)]
[{1, 2}, {1, 3}, {2, 3}]
关于python - 在 Python 中生成所有大小为 k 的子集(包含 k 个元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7378180/