How to get all combination from multiple lists?

Viewed 6449

I am not sure that my question is correct but I don't know how to explain it otherwords. So I've got some lists like

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']

And i need to get something like:

result = [
    ['11', '21', '31'],
    ['11', '21', '32'],
    ['11', '22', '31'],
    ['11', '22', '32'],
    ['12', '21', '31'],
    ['12', '21', '32'],
    ['12', '22', '31'],
    ['12', '22', '32']
]
5 Answers

A solution without using any library:

def subproblem(list_a, list_b):
    c = list()
    for i, a_i in enumerate(list_a):
        for j, b_j in enumerate(list_b):
            c.append(a_i + [b_j])
    return c


def multi_lists_find_all_combination(lists):
    com = [[]]
    if len(lists) == 1:
        return lists[0]
    for i in range(0, len(lists)):
        print(i)
        com = subproblem(com, lists[i])
    return com

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']

ans = multi_lists_find_all_combination([a,b,c])

Related