Generating all combinations of a list in python

后端 未结 7 2150
不思量自难忘°
不思量自难忘° 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 20:00

    Are you looking for itertools.permutations instead?

    From help(itertools.permutations),

    Help on class permutations in module itertools:
    
    class permutations(__builtin__.object)
     |  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)
    

    Sample Code :

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

    From Wikipedia, the difference between permutations and combinations :

    Permutation :

    Informally, a permutation of a set of objects is an arrangement of those objects into a particular order. For example, there are six permutations of the set {1,2,3}, namely (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), and (3,2,1).

    Combination :

    In mathematics a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter.

提交回复
热议问题