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

问题描述 投票:0回答:5

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

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然而,我的问题是更复杂的问题。

python python-3.x list nested-lists
5个回答
3
投票

这就是诀窍 -

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']]

2
投票

与@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']]

-1
投票

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

>>> 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']]

-1
投票

您可以使用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']]

-2
投票

这是你在找什么?

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
© www.soinside.com 2019 - 2024. All rights reserved.