我有一组值,想创建包含 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 个元素)的所有子集
发布评论