我想创建列表列表的可能组合列表(示例将更好地解释)
list=[[a,b],[c,d],[f]]
结果应为
acf
adf
bcf
bdf
列表的长度可以变化,变量列表中列表的长度也可以变化。我如何以编程方式创建这个/这些循环? (最好用Python或伪语言解释)
答案 0 :(得分:5)
这就是itertools.product
的用途:
>>> lst = ['ab','cd','f']
>>> from itertools import product
>>> list(product(*lst))
[('a', 'c', 'f'), ('a', 'd', 'f'), ('b', 'c', 'f'), ('b', 'd', 'f')]
答案 1 :(得分:1)
import itertools
list=[['a','b'],['c','d'],['f']]
for comb in itertools.product(*list):
print ''.join(comb)
答案 2 :(得分:0)
您可以递归地执行此操作:
def printCombos(arrays, combo):
if len(arrays) == 0:
print combo
else:
for i in arrays[0]:
combo.append(i)
printCombos(arrays[1:], combo)
combo.pop()
l=[['a','b'],['c','d'],['f']]
printCombos(l, [])
答案 3 :(得分:0)
curlist = []
for firstobj in listoflists[0]:
for secondobj in listoflists[1]:
for lastobj in listoflists[2]:
curlist.append(firstobj)
curlist.append(secondobj)
curlist.append(lastobj)
print ','.join(curlist)