[Numpy-discussion] how do I list all combinations

Alan G Isaac aisaac@american....
Sun Dec 30 12:25:07 CST 2007

On Wed, 26 Dec 2007, Mathew Yeates apparently wrote: 
> r1=["dog","cat"] 
> r2=[1,2] 
> I want to return [["dog",1],["dog",2],["cat",1],["cat",2]] 

This is a Cartesian product.

Sage has ``cartesian_product_iterator`` for this.

Here is a Cookbook implementation.
The generator may be adequate to your needs.

Here is a recursive implementation that does not use 
multi-dimensional indexing:

def set_product(*sets):
    last_set = sets[-1]
    drop_last = sets[:-1]
    if drop_last:
        result = set( x+(y,)
                      for x in set_product(*drop_last)
                      for y in last_set )
        result = set( (y,) for y in last_set )
    return result

Sorry for a late reply.  I'm catching up on email...

Alan Isaac

More information about the Numpy-discussion mailing list