Generate all subsets of size k (containing k elements) in Python

前端 未结 3 808
后悔当初
后悔当初 2020-12-03 14:31

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-elem

3条回答
  •  既然无缘
    2020-12-03 14:59

    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))
    
    

    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}]
    

提交回复
热议问题