假设我有一个嵌套的字符串列表
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 但是,我的问题是更复杂的问题。
答案 0 :(得分: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']]
答案 1 :(得分: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']]
答案 2 :(得分:-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']]
答案 3 :(得分:-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']]
答案 4 :(得分:-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