(newbie) N-uples from list of lists

vd12005 at yahoo.fr vd12005 at yahoo.fr
Wed Nov 23 15:00:15 EST 2005


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