Python中一组列表的所有可能排列

在Python中,我有一个n个列表的列表,每个列表具有可变数量的元素。 如何创建包含所有可能排列的单个列表:

例如

[ [ a, b, c], [d], [e, f] ]

我想要

[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]

请注意,我事先不知道n。 我以为itertools.product是正确的方法,但它需要我提前知道参数的数量

Ian Davis asked 2020-08-05T02:26:16Z
3个解决方案
75 votes

使用2997361879972054054017时,您不需要事先知道2997361879972054054016

>>> 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')]
John La Rooy answered 2020-08-05T02:26:35Z
4 votes

itertools.product对我有用。

>>> 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)]
>>>
Wai Yip Tung answered 2020-08-05T02:26:55Z
3 votes

您可以通过多级列表理解来做到这一点:

>>> 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']]
Daniel DiPaolo answered 2020-08-05T02:27:15Z
translate from https://stackoverflow.com:/questions/2853212/all-possible-permutations-of-a-set-of-lists-in-python