在 Python 中生成大小为 k(包含 k 个元素)的所有子集 [英] Generate all subsets of size k (containing k elements) in Python

查看:69
本文介绍了在 Python 中生成大小为 k(包含 k 个元素)的所有子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组值,想创建包含 2 个元素的所有子集的列表.

例如,源集 ([1,2,3]) 具有以下 2 元素子集:

set([1,2]), set([1,3]), set([2,3])

有没有办法在python中做到这一点?

解决方案

看起来像你想要的 itertools.combinations:

<预><代码>>>>列表(itertools.combinations((1, 2, 3), 2))[(1, 2), (1, 3), (2, 3)]

如果你想要集合,你必须显式地转换它们.如果您不介意使用迭代而不是列表,并且您使用的是 Python 3,则可以使用 map:

<预><代码>>>>s = 集合((1, 2, 3))>>>地图(设置,itertools.combinations(s,2))<0x10cdc26d8处的映射对象>

要一次查看所有结果,可以将map 的输出传递给list.(在 Python 2 中,map 的输出自动是一个列表.)

<预><代码>>>>列表(地图(设置,itertools.combinations(s,2)))[{1, 2}, {1, 3}, {2, 3}]

然而,如果你知道你需要一个列表,列表理解稍微好一点(h/t Jacob Bowyer):

<预><代码>>>>[在 itertools.combinations(s, 2) 中为 i 设置(i)][{1, 2}, {1, 3}, {2, 3}]

I have a set of values and would like to create list of all subsets containing 2 elements.

For example, a source set ([1,2,3]) has the following 2-element subsets:

set([1,2]), set([1,3]), set([2,3])

Is there a way to do this in python?

解决方案

Seems like you want itertools.combinations:

>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]

If you want sets you'll have to convert them explicitly. If you don't mind an iterable instead of a list, and you're using Python 3, you can use map:

>>> s = set((1, 2, 3))
>>> map(set, itertools.combinations(s, 2))
<map object at 0x10cdc26d8>

To view all the results at once, you can pass the output of map to list. (In Python 2, the output of map is automatically a list.)

>>> list(map(set, itertools.combinations(s, 2)))
[{1, 2}, {1, 3}, {2, 3}]

However, if you know you'll need a list, a list comprehension is marginally better (h/t Jacob Bowyer):

>>> [set(i) for i in itertools.combinations(s, 2)]
[{1, 2}, {1, 3}, {2, 3}]

这篇关于在 Python 中生成大小为 k(包含 k 个元素)的所有子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆