python - 在 Python 中生成所有大小为 k 的子集(包含 k 个元素)

标签 python set tuples subset

我有一组值,想创建包含 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/

相关文章:

c++ - 如何为集合 C++ 建立比较器

python - 从元组中删除元素

Python:包含元组和长整数的列表

python - 我很难在 python 中使用 mincemeat 进行 mapreduce 来计算不同文件的字数

c++ - std::set 错误:»operator<« 不匹配

Python - Pandas - 计算字符串中字符出现的次数并替换字符串值

C++ 设置使用线性探测?

tuples - OCaml中有pair构造函数吗?

python - 在 Python 中使用 Rasterbar libtorrent 进行樱桃选择

python - 使用异步服务器的长时间运行的任务