views:

160

answers:

1

Consider a tuple v = (a,b,c) and a generator function generate(x) which receives an item from the tuple and generates several options for each item.

What is the pythonic way of generating a set of all the possible combinations of the result of generate(x) on each item in the tuple?

I could do this:

v = (a,b,c)
for d in generate(v[0]):
    for e in generate(v[1]):
        for f in generate(v[2]):
            print d,e,f

but that's just ugly, plus I need a generic solution.

+6  A: 

Python 2.6 has the function itertools.product() that does what you want:

import itertools
v = (a, b, c)
for d, e, f in itertools.product(*(generate(x) for x in v)):
  print d, e, f

From the docs:

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

Ayman Hourieh
Looks to be helpful, how would I iterate over the result?
Yuval A
@Yuval: `for i in product(*(generate(x) for x in v)): do_whatever_you_want(i)`
KennyTM
Wicked. and the answer is already updated to reflect that...
Yuval A
@Yuval: It returns a generator that lists all combinations. I've updated my answer to show how to iterate over the results.
Ayman Hourieh
Thanks Ayman!...
Yuval A
@Yuval: Happy to help!
Ayman Hourieh