Python generates all n substitutions from n lists

I have n lists of different lengths for which I want to create all possible permutations.

those. if a=[1,2]

u b=[3,4,5]

then i would like to get res=[[1,3],[1,4],[1,5],[2,3],[2,4],[2,5]]

i tried to achieve this using a recursive function which turned out to be not very efficient and not very pythonic. How does an experienced python programmer handle the problem?

+3


source to share


3 answers


He called the Cartesian product of two sequences.

It is already available in Python as a library function: . itertools.product



Example:

>>> import itertools
>>> a = [1, 2]
>>> b = [3, 4, 5]
>>> list(itertools.product(a, b))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

      

+14


source


you can do it with the product function in itertools,



import itertools
a = [1,2]
b = [3, 4, 5]
out = list(itertools.product(a,b))
print out
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

      

0


source


itertools is definitely the way to go, but if you don't want to take the easy routes .....

def print_permutations(lists, perms=[]):
    if not lists:
        print perms
    else:
        current_layer = lists[0]
        remaining_layers = lists[1:]
        for word in current_layer:
            print_permutations(remaining_layers, perms + [word])



l = (('quick', 'lazy'), ('brown', 'black', 'grey'), ('fox', 'dog'))
print_permutations(l)

      

0


source







All Articles