python:任意数量生成器的笛卡尔积

时间:2021-04-18 21:53:35

标签: python-3.x generator

有没有办法获得与 itertools.product 相同的输出,但对于生成器而不是迭代器? 对于两个生成器,我们可以这样做:

for a in generator_1: 
    g2_dup, generator_2 = itertools.tee(generator_2)
    for b in g2_dup:
        yield (a, b)

但这意味着我们需要为每个生成器创建一个“for 循环”。 有没有办法应用相同的概念,但适用于任意数量的生成器?即用户传递生成器列表,代码应生成这些生成器的笛卡尔积:

def generators_product(all_generators:'list[Generator]'):
    #if there are 4 generators: g1,g2,g3,g4, then output should yield: 
    #(g1[0],g2[0],g3[0],g4[1]), (g1[0],g2[0],g3[0],g4[2]), ... ,(g1[0],g2[0],g3[0],g4[-1])
    #(g1[0],g2[0],g3[1],g4[0]),...etc.
    #those generators do other logic operations when yielded, 
    #so it is important that they 'yield' one output at a time (i.e. can't consume it all to a list)

0 个答案:

没有答案