python组合算法的问题

求组合数的问题:

假设我有2个list

A=[a1,a2]
B=[b1,b2]

从这个2个列表中各取一个值,形成一个组合比如[a1,b1],或者 [a1,b2]这样的,代码这样写:

for a in A:
    for b in B:
        res.append([a,b])

但如果我有3个列表呢,代码这样写:

for a in A:
    for b in B:
        for c in C:
            res.append([a,b,c])

如果我有4个这样的列表,这样可以嵌套4个for

但如果我列表数是不固定的呢,如果有100个列表,我不能手动把for循环嵌套100次吧,有什么好方法呢?

from itertools import product
loop_val = [a,b,c,d]
rst = list(product(*loop_val))

2019-10-11: 没看清楚题目,答案跟题目不符,请忽略。。。

假设 lists 是一个包含你所有list的list: [A, B, C, ...]

list(zip(*lists))

这样的话,每个元素是一个tuple: (a1, b1, c1, ...), 如果需要每个元素也是list,可以

 [list(val) for val in zip(*lists)]

# -*- coding: UTF-8 -*-
def initcomb(seed):
    res = []
    for a in seed:
        item = []
        item.append(a)
        res.append(item)
    return res      
def comb(seed, lst):
    res = []
    for a in seed:
        for b in lst:
            item = list(a)
            item.append(b)
            res.append(item)
    return res

A=['a1','a2']
B=['b1','b2']
C=['c1','c2']
l = initcomb(A)
l = comb(l,B)
l = comb(l,C)
print(l)

[['a1', 'b1', 'c1'], ['a1', 'b1', 'c2'], ['a1', 'b2', 'c1'], ['a1', 'b2', 'c2'], ['a2', 'b1', 'c1'], ['a2', 'b1', 'c2'], ['a2', 'b2', 'c1'], ['a2', 'b2', 'c2']]

写成循环,任意多个

# -*- coding: UTF-8 -*-
def initcomb(seed):
    res = []
    for a in seed:
        item = []
        item.append(a)
        res.append(item)
    return res      
def comb(seed, lst):
    res = []
    for a in seed:
        for b in lst:
            item = list(a)
            item.append(b)
            res.append(item)
    return res

A=['a1','a2']
B=['b1','b2']
C=['c1','c2']
D=['d1','d2']
lst = [A,B,C,D]
l = initcomb(lst[0])
for i in range(1,len(lst)):
    l = comb(l,lst[i])
print(l)

[['a1', 'b1', 'c1', 'd1'], ['a1', 'b1', 'c1', 'd2'], ['a1', 'b1', 'c2', 'd1'], ['a1', 'b1', 'c2', 'd2'], ['a1', 'b2', 'c1', 'd1'], ['a1', 'b2', 'c1', 'd2'], ['a1', 'b2', 'c2', 'd1'], ['a1', 'b2', 'c2', 'd2'], ['a2', 'b1', 'c1', 'd1'], ['a2', 'b1', 'c1', 'd2'], ['a2', 'b1', 'c2', 'd1'], ['a2', 'b1', 'c2', 'd2'], ['a2', 'b2', 'c1', 'd1'], ['a2', 'b2', 'c1', 'd2'], ['a2', 'b2', 'c2', 'd1'], ['a2', 'b2', 'c2', 'd2']]

import copy

input_list = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']]
result = []

def func(input_list, x=None):
if not x:
x = []
if input_list:
list_pop = input_list.pop(0)
for i in list_pop:
func(copy.deepcopy(input_list), x + [i])
else:
result.append(x)

if name == '__main__':
func(input_list)
print(result)
类似的思路把,不确定层数的循环可以用递归