Python: combining a list of lists in an algebraic way

In mathematics, when you have two sets of words A = {foo, bar} and B = {x, y}, then the algebraic product (or each of each) is AB = {foox, fooy, barx, Bary}. I would like to in Python. For two sets of words (= list of lists):

A = [ [0,1], [2,3] ]
B = [ [4,5], [6,7] ]

I would like to combine them with each other:

AB = [ [0,1,4,5], [0,1,6,7], [2,3,4,5], [2,3,6,7] ]

It is not so difficult, it can be done with product:

AB = [ a+b for (a,b) in itertools.product(A,B) ]

However, I have a list of "sets" (aka, a list of lists of lists)

A = [ [0,1], [2,3] ]
B = [ [4,5], [6,7] ]
C = [ [4,5], [6,7] ]
SETS = [A,B,C]

Now I can do it manually

ABC = [ a+b+c for (a,b,c) in itertools.product(A,B,C) ]

But I can not do this if I have 20 sets for concatenation. So, how to write a definition ABCthat will use only SETSand take any size?

+4
3
ABC = [ sum(z, []) for z in itertools.product(*SETS) ]

product(*SETS) product(A, B, C). .

sum(z, []) a + b + c + [].

sum, . O (n ^ 2) .

:

sum(). , - ''.join(). , . math.fsum(). , itertools.chain().

:

from itertools import chain, product
ABC = [ list(chain(*z)) for z in product(*SETS) ]

, - , :

ABC = [ list(chain.from_iterable(z)) for z in product(*SETS) ]

, map:

ABC = map(list, map(chain.from_iterable, product(*SETS)))
+7

, : itertools.product(*SETS). , ():

def concat(seqs):
    result = []
    for seq in seqs:
        result.extend(seq)
    return result

: [concat(prod) for prod in itertools.product(*SETS)]

+1

First use the *unpack operator for the SETSfunction argument itertools.product().

    itertools.product(*SET)

Then, using import operator, combine the result from this:

    product = [ reduce(operator.add, tuple) for tuple in itertools.product(*SET) ]

This works because if a variable tuple ([0,1], [4,5], [8,9]), reduce(operator.add, tuple)still gives you [0,1,4,5,8,9].

+1
source

Source: https://habr.com/ru/post/1526199/


All Articles