How to get all possible combination of elements from 2-dimensional list in python?

I did not find a better way to formulate this question in the title. If you can, please edit.

I have a list of such lists:

a = [['a','b'],[1,2]]

Now, I need a function that spits out all possible combinations as follows:

[['a',1],['a',2],['b',1],['b',2]]

where neither the number of lists in a is known in advance, nor the length of each of the auxiliary lists known in advance, but all combinations that come out should contain one element from each sublist.

+5
source share
3 answers

You need to itertools.product():

>>> list(itertools.product(*a))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
+11
source

This could be what itertools.product()(what Sven says):

def combs(list1, list2):
    results = []
    for x in list1:
        for y in list2:
            l.append([x,y])
    return results
0

, , combs_r accum digest head ( ) accum0, ( "" ) tail ( ) accum0.

, combs_r , . , Python, .

, .

def combs(ll):
    if len(ll) == 0:
        return []
    if len(ll) == 1:
         return [[item] for item in ll[0]]
    elif len(ll) == 2:
        return lmul(ll[0], [[item] for item in ll[1]])
    else:
        return combs_r(ll[1:], ll[0])

def combs_r(ll, accum):
    head = ll[0]
    tail = ll[1:]
    accum0 = []
    accum0 = lmul(head, accum)
    if len(tail) == 0:
        return accum0
    else:
        return combs_r(tail, accum0)

def lmul(head, accum):
    accum0 = []
    for ah in head:
        for cc in accum:
            #cc will be reused for each ah, so make a clone to mutate
            cc0 = [x for x in cc]
            cc0.append(ah)
            accum0.append(cc0)
    return accum0

sampleip = [['a','b','c'],[1,2], ['A', 'B']]
sampleip2 = [['a','b','c'],[1,2]]
sampleip1 = [['a','b','c']]
sampleip0 = []
print combs(sampleip0)
print combs(sampleip1)
print combs(sampleip2)
print combs(sampleip)
0

All Articles