如何将 itertools.product 应用于 Python 中的嵌套列表

How to apply itertools.product to a nested list in Python

假设我有一个嵌套的字符串列表

lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]

我想从嵌套列表生成所有可能的组合,如下所示:

new_lst = [['a', 'b', 'd'],
           ['a', 'b', 'e', 'f'],
           ['a', 'c', 'd'],
           ['a', 'c', 'e', 'f']]

我发现了一些可能与我的问题相关的问题。 how to produce a nested list from two lists in python 不过,我的问题比较复杂。

这是解决问题的方法 -

import itertools
lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
outp = list(itertools.product(*lst))
out = []
for i in outp:
    temp = []
    for j in i:
        if isinstance(j, list):
            for k in j:
                temp.append(k)
        else:
            temp.append(j)
    out.append(temp)
print(out)

首先使用 itertools.product 形成输出材料,然后简单地以嵌套列表被展平的方式对其进行格式化。

输出

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

这是您要找的吗?

from itertools import permutations
lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
list(permutations(lst))

否则,试试这个:

lst = ['a','b','c','d','e','f']
list(permutations(lst))   ##will return all possible combos

与@VivekKalyanarangan 类似,但具有适当的扁平化器:

>>> def flatten(nl):
...     for e in nl:
...         if isinstance(e, str):
...             yield e
...             continue
...         try:
...             yield from flatten(e)
...         except TypeError:
...             yield e
... 

>>> lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
>>> 
>>> list(map(list, map(flatten, itertools.product(*lst))))
[['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]

另一种使用列表理解的方式

>>> ls = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
>>> res = ['']
>>> for elem in ls:
...     res = [list(j) + list(e) for j in res for e in elem]
... 
>>> res
[['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]

您可以使用 chain.from_iterable() 来拉平结果:

from itertools import product, chain

lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]

[list(chain.from_iterable(i)) for i in product(*lst)]
# [['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]