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

编程入门 行业动态 更新时间:2024-10-28 02:25:05
本文介绍了在 Python 中生成大小为 k(包含 k 个元素)的所有子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

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

解决方案

看起来像你想要的 itertoolsbinations:

>>>列表(itertoolsbinations((1, 2, 3), 2))[(1, 2), (1, 3), (2, 3)]

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

>>>s = 集合((1, 2, 3))>>>地图(设置,itertoolsbinations(s,2))<0x10cdc26d8处的映射对象>

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

>>>列表(地图(设置,itertoolsbinations(s,2)))[{1, 2}, {1, 3}, {2, 3}]

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

>>>[在 itertoolsbinations(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 itertoolsbinations:

>>> list(itertoolsbinations((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, itertoolsbinations(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, itertoolsbinations(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 itertoolsbinations(s, 2)] [{1, 2}, {1, 3}, {2, 3}]

更多推荐

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

本文发布于:2023-11-30 00:23:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648104.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子集   元素   大小   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!