问题描述
我有一组值,想创建包含 2 个元素的所有子集的列表.
I have a set of values and would like to create list of all subsets containing 2 elements.
例如,源集 ([1,2,3]) 具有以下 2 元素子集:
For example, a source set ([1,2,3]) has the following 2-element subsets:
set([1,2]), set([1,3]), set([2,3])
有没有办法在 python 中做到这一点?
Is there a way to do this in python?
推荐答案
好像你想要 itertools.combinations:
Seems like you want itertools.combinations:
>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]
如果你想要集合,你必须明确地转换它们.如果您不介意使用迭代而不是列表,并且您使用的是 Python 3,则可以使用 map:
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>
要一次查看所有结果,您可以将 map 的输出传递给 list.(在 Python 2 中,map 的输出自动是一个列表.)
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}]
但是,如果您知道自己需要一个列表,那么列表理解会稍微好一些(h/t Jacob Bowyer):
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 个元素)的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)