[Numpy-discussion] how do I list all combinations

Charles R Harris charlesr.harris at gmail.com
Wed Dec 26 16:30:43 EST 2007


On Dec 26, 2007 1:45 PM, Keith Goodman <kwgoodman at gmail.com> wrote:

> On Dec 26, 2007 12:22 PM, Mathew Yeates <myeates at jpl.nasa.gov> wrote:
> > I have an arbitrary number of lists. I want to form all possible
> > combinations from all lists. So if
> > r1=["dog","cat"]
> > r2=[1,2]
> >
> > I want to return [["dog",1],["dog",2],["cat",1],["cat",2]]
> >
> > It's obvious when the number of lists is not arbitrary. But what if
> > thats not known until runtime?
>
> Would this work?
>
> Make a function that takes two inputs (a list of lists and a list) and
> returns a list of lists that contains all possible combinations.
> Iterate through all lists by calling the function with the output of
> the previous call (a list of lists) and the next list.
> ____
>

Yeah, you can do it with recursion, but I don't think it would be quite as
efficient. An example of the explicit approach, define the following
generator:

def count(listoflists) :
    counter = [i[0] for i in listoflists]
    maxdigit = [len(i) - 1 for i in listoflists]
    yield counter
    while True :
        i = 0;
        while i < len(counter) and counter[i] == maxdigit[i] :
            counter[i] = 0
            i += 1
        if i < len(counter) :
            counter[i] += 1
            yield counter
        else :
            return



In [30]: a = ['dog', 'cat', 'horse']

In [31]: b = ['red', 'black']

In [32]: c = [a,b]

In [33]: for i in count.count(c) : print [c[j][i[j]] for j in range(len(c))]
   ....:
['dog', 'red']
['cat', 'red']
['horse', 'red']
['dog', 'black']
['cat', 'black']
['horse', 'black']

___________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20071226/5806773c/attachment.html>


More information about the NumPy-Discussion mailing list