(newbie) N-uples from list of lists

bonono at gmail.com bonono at gmail.com
Fri Nov 25 12:10:02 EST 2005


This is my attempt :

def cross(seq):
     r=[[]]
    for x in seq:
        r = [ a + b for a in r for b in [[i] for i in x ]]
    return r

It is not very efficient though as it would loop through the
intermediate list produced multiple times.

vd12005 at yahoo.fr wrote:
> Hello,
>
> i think it could be done by using itertools functions even if i can not
> see the trick. i would like to have all available "n-uples" from each
> list of lists.
> example for a list of 3 lists, but i should also be able to handle any
> numbers of items (any len(lol))
>
> lol = (['a0', 'a1', 'a2'], ['b0', 'b1'], ['c0', 'c1', 'c2', 'c3'])
>
> =>
>
>
> [('a0', 'b0', 'c0'), ('a0', 'b0', 'c1'), ('a0', 'b0', 'c2'), ('a0',
> 'b0', 'c3'), ('a0', 'b1', 'c0'), ('a0', 'b1', 'c1'), ('a0', 'b1',
> 'c2'), ('a0', 'b1', 'c3'), ('a1', 'b0', 'c0'), ('a1', 'b0', 'c1'),
> ('a1', 'b0', 'c2'), ('a1', 'b0', 'c3'), ('a1', 'b1', 'c0'), ('a1',
> 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b1', 'c3'), ('a2', 'b0',
> 'c0'), ('a2', 'b0', 'c1'), ('a2', 'b0', 'c2'), ('a2', 'b0', 'c3'),
> ('a2', 'b1', 'c0'), ('a2', 'b1', 'c1'), ('a2', 'b1', 'c2'), ('a2',
> 'b1', 'c3')]
>
> maybe tee(lol, len(lol)) can help ?
>
> it could be done by a recursive call, but i am interested in using and
> understanding generators.
>
> i also have found a convenient function, here :
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65285 (paste
> below)
> but i am curious of how you will do it or refactorize this one with
> generators...
>
> def permuteflat(*args):
>     outs = []
>     olen = 1
>     tlen = len(args)
>     for seq in args:
>         olen = olen * len(seq)
>     for i in range(olen):
>         outs.append([None] * tlen)
>     plq = olen
>     for i in range(len(args)):
>         seq = args[i]
>         plq = plq / len(seq)
>         for j in range(olen):
>             si = (j / plq) % len(seq)
>             outs[j][i] = seq[si]
>     for i in range(olen):
>         outs[i] = tuple(outs[i])
>     return outs
> 
> many thanx




More information about the Python-list mailing list