产生发电机时如何拉平产量?

How to flatten out the yield when yielding a generator?

我有这个功能 g() 我的目标是产生类似于 product() 的结果,但每组字符的出现次数受到限制。所以在下面的代码中,而不是做 product(a, repeat=3) g() 应该产生所有组合,其中来自 a 的字符出现 2 次,来自 b 的字符出现 1 次。这是我拥有的:

from itertools import permutations, product

a='ABC'
b=['*', '%3A']
l=[a]*2+[b]

def g(list):
    for p in permutations(list):
        yield product(*p)


result=g(l)

所以我面临的问题是,当我 yield 结果时,我得到了一个使用起来很痛苦的嵌套迭代器,而当我使用 return 时,它只是 returns生成器仅对应于第一个循环,就像我所做的一样:g() 仅由 def g(): return product(*next(permutations(list))) 组成。

如果您是 python 3.3 或更高版本,您可以使用 PEP 380: Syntax for Delegating to a Subgenerator ... 只需 yield from

from itertools import permutations, product

a='ABC'
b=['*', '%3A']
l=[a]*2+[b]

def g(list):
    for p in permutations(list):
        yield from product(*p)


result=g(l)