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

logistix logstx at bellatlantic.net
Tue May 28 17:30:01 EDT 2002


This is probably alot slower than actually writing multiple crossproduct
functions, but it's generic.  You might be better off writing a function
with a big if...elif... construct that checks the list count and returns the
appropriate list comprehension.

>>> list1 = [1,2]
>>> list2 = ['a','b','b']
>>> list3 = [1,2,3,4]

def crossProduct(*listOfLists):
...  first = listOfLists[0]
...  retVal = []
...  for item in first:
...   retVal.append( [item] )
...  i = 1
...  while i < len(listOfLists):
...   next = listOfLists[i]
...   retVal = [x[:]+[y] for x in retVal for y in next]
...   i += 1
...  return retVal
...
>>> crossProduct(list1)
[[1], [2]]
>>> crossProduct(list1,list2)
[[1, 'a'], [1, 'b'], [1, 'b'], [2, 'a'], [2, 'b'], [2, 'b']]
>>> crossProduct(list1,list2,list3)
[[1, 'a', 1], [1, 'a', 2], [1, 'a', 3], [1, 'a', 4],
[1, 'b', 1], [1, 'b', 2], [1, 'b', 3], [1, 'b', 4],
[1, 'b', 1], [1, 'b', 2], [1, 'b', 3], [1, 'b', 4],
[2, 'a', 1], [2, 'a', 2], [2, 'a', 3], [2, 'a', 4],
 [2, 'b', 1], [2, 'b', 2], [2, 'b', 3], [2, 'b', 4],
[2, 'b', 1], [2, 'b', 2], [2, 'b', 3], [2, 'b', 4]]

--
-

"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