All possible permutations of a set of lists in Python

后端 未结 3 655
离开以前
离开以前 2020-11-30 01:36

In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:

For example

相关标签:
3条回答
  • 2020-11-30 02:06

    You can do it with a multi-level list comprehension:

    >>> L1=['a','b','c']
    >>> L2=['d']
    >>> L3=['e','f']
    >>> [[i,j,k] for i in L1 for j in L2 for k in L3]
    [['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]
    
    0 讨论(0)
  • 2020-11-30 02:13

    itertools.product works for me.

    >>> l=[ [ 1, 2, 3], [4], [5, 6] ]
    >>> list(itertools.product(*l))
    [(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
    >>> l=[ [ 1, 2, 3], [4], [5, 6],[7,8] ]
    >>> list(itertools.product(*l))
    [(1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8), (3, 4, 5, 7), (3, 4, 5, 8), (3, 4, 6,
     7), (3, 4, 6, 8)]
    >>>
    
    0 讨论(0)
  • 2020-11-30 02:17

    You don't need to know n in advance to use itertools.product

    >>> import itertools
    >>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
    >>> list(itertools.product(*s))
    [('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]
    
    0 讨论(0)
提交回复
热议问题