开发者

Nested generator functions in python

开发者 https://www.devze.com 2022-12-25 05:52 出处:网络
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.

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 u开发者_开发知识库gly, plus I need a generic solution.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消