variable X procuct - [(x,y) for x in list1 for y in list2]
Chris Liechti
cliechti at gmx.net
Tue May 28 17:15:28 EDT 2002
steindl fritz <python at floSoft.org> wrote in
news:1022619068.34271 at newsmaster-04.atnet.at:
> first - maybe sombody can help me with the english expression for the
> german word 'kreuzprodukt' - this my question is dealing with
try: http://dict.tu-chemnitz.de/
"cross product"
> -----------------------------------------------
>
> 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
you're sure you want to program this yourself? there is numpy, i think it
can handle that.
anyway, this one is taking list of list (or tuples):
>>> xp=lambda l1,l2:[x+y for x in l1 for y in l2]
>>> xp([(1, 'a'), (2, 'b')], [(1, 'a'), (2, 'b')])
[(1, 'a', 1, 'a'), (1, 'a', 2, 'b'), (2, 'b', 1, 'a'), (2, 'b', 2, 'b')]
zip can be used to transform a list to a list of list (trasposed)
that way you can use it nested:
>>> xp(xp(zip([1,2]), zip([a,b,c])), zip([3,4]))
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list