在 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 是正确的方法,但它需要我提前知道参数的数量
最佳答案
使用itertools.product
n
>>> 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')]
关于python - Python中一组列表的所有可能排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2853212/