【发布时间】:2012-11-26 23:48:14
【问题描述】:
有时我发现自己在 Python 中编写递归生成器。这是recent example:
def comb(input, lst = [], lset = set()):
if lst:
yield lst
for i, el in enumerate(input):
if lset.isdisjoint(el):
for out in comb(input[i+1:], lst + [el], lset | set(el)):
yield out
for c in comb([[1, 2, 3], [3, 6, 8], [4, 9], [6, 11]]):
print c
算法的细节并不重要。我将它作为一个完整的真实世界插图包含在内,以便为这个问题提供一些背景信息。
我的问题是关于以下构造:
for out in comb(...):
yield out
这里,comb() 是生成器的递归实例化。
每次我必须拼出for: yield 循环时,都会让我畏缩。这真的是 在 Python 中编写递归生成器的方式,还是有更好的(更惯用的、性能更高的等)替代方案?
【问题讨论】:
-
Python 3.3 具有
yield from <generator>构造,但尚未向后移植。 -
在 Py3.3 上使用新的
yield from语法。它是为这些事情而设计的 -
天哪!可惜我还在 Python 2.x 上。 :(
-
@Wessie:+1,但是……“还没有被反向移植”?您预计何时将其向后移植,以及移植到什么版本?没有将来的版本可以将其反向移植到。
-
@abarnert:您确实是对的,它不会被反向移植到早期版本中的语言结构中。我记得Pure Python yield from.
标签: python recursion generator