假设我有一个嵌套的字符串列表
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']]
与@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']]
这是你在找什么?
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