All possible permutations of a set of lists in Python

后端 未结 3 657
离开以前
离开以前 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: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')]
    

提交回复
热议问题