我有一组值,想创建包含 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 个元素)的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!