Generating all combinations of a list in python

后端 未结 7 2148
不思量自难忘°
不思量自难忘° 2020-11-27 19:29

Here\'s the question:

Given a list of items in Python, how would I go by to get all the possible combinations of the items?

There are several similar questio

7条回答
  •  自闭症患者
    2020-11-27 19:56

    Use itertools.permutations:

    >>> import itertools
    >>> stuff = [1, 2, 3]
    >>> for L in range(0, len(stuff)+1):
            for subset in itertools.permutations(stuff, L):
                    print(subset)
    ...         
    ()
    (1,)
    (2,)
    (3,)
    (1, 2)
    (1, 3)
    (2, 1)
    (2, 3)
    (3, 1)
    ....
    

    help on itertools.permutations:

    permutations(iterable[, r]) --> permutations object
    
    Return successive r-length permutations of elements in the iterable.
    
    permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
    >>> 
    

提交回复
热议问题