在 Python 中,我有一个包含 n 个列表的列表,每个列表都有可变数量的元素。如何创建包含所有可能排列的单个列表:
例如
[ [ a, b, c], [d], [e, f] ]
I want
[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]
注意我事先不知道n。我认为 itertools.product 将是正确的方法,但它要求我提前知道参数的数量
你不需要知道n提前使用itertools.product
n
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')]