variable X procuct - [(x,y) for x in list1 for y in list2]

Raymond Hettinger python at rcn.com
Tue May 28 17:19:49 EDT 2002


def CartesianProduct(*args):
    ans = [()]
    for arg in args:
        ans = [ list(x)+[y] for x in ans for y in arg]
    return ans

print CartesianProduct([1,2], list('abc'), 'do re mi'.split())


Raymond Hettinger


"steindl fritz" <python at floSoft.org> wrote in message
news:1022619068.34271 at newsmaster-04.atnet.at...
> hi list,
>
> first - maybe sombody can help me with the english expression for the
> german word 'kreuzprodukt' - this my question is dealing with
>
> -----------------------------------------------
>
> example -
>
> list1 = [1, 2]
> list2 = [a, b, c]
>
> [(x,y) for x in list1 for y in list2]
>
> the result is the "kreuzprodukt"
> [(1,a), (1,b), (1,c), (2,a), (2,b), (2,c)]
>
> -----------------------------------------------
>
> question -
>
> i need to keep the number of lists variable
>
> e.g. the next case should handle three lists
>
> [(a1, a2, a3) for a1 in list1 for a2 in list2 for a3 in list3]
>
> i cannot put variables into this algorythm or they don't do what i expect
> maybe there is a simple solution, but i cannot find it
>
>
> <thx>
>
> fritz
> (-:fs)
>





More information about the Python-list mailing list