简体   繁体   English

python中的嵌套生成器函数

[英]Nested generator functions in python

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. 考虑一个元组v = (a,b,c)和一个生成函数generate(x) ,它从元组接收一个项目并为每个项目生成几个选项。

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? 什么是在元组中的每个项目上生成一组所有可能的generate(x)结果的组合的pythonic方法?

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. 但那只是丑陋的,而且我需要一个通用的解决方案。

Python 2.6 has the function itertools.product() that does what you want: Python 2.6具有函数itertools.product() ,可以执行您想要的操作:

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循环。 For example, product(A, B) returns the same as ((x,y) for x in A for y in B). 例如,乘积(A,B)与A中的x的((x,y)相同,对于B中的y,返回相同的值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM