Simple cartesian product

Charles G Waldman cgw at fnal.gov
Wed Jan 5 15:42:00 EST 2000


Magnus L. Hetland writes:
 > > 
 > > What I'm missing here is a simple expression which will make a list
 > > like [1, 2, 3, 4] into [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] (if
 > > len(b)==3)...
 > 

If you use Numeric, the "repeat" function does exactly this:

from Numeric import *

x = array([1,2,3,4])
xx = repeat(x,len(x)*(3,))


Of course if you're going to use Numeric, you could (ab)use "dot" to
do what you want:

#!/usr/bin/env python

from Numeric import *
class X:
    def __init__(self,val):
        self.val = val
    def __mul__(self,other):
	return (self.val,other.val)
    def __repr__(self):
        return repr(self.val)
    def __str__(self):
        return str(self.val)

l1=['a','b','c']
l2=['d','e','f']

v1=array(map(X,l1))
v2=array(map(X,l2))

v1.shape=3,1
v2.shape=1,3

print dot(v1,v2)





More information about the Python-list mailing list