如何 return 来自另一个函数的生成器

How to return a generator from another function

我有一个生成器函数,我想从另一个函数调用它,return 生成器获得。我可以在这里看到两种方法 -

请注意,以下函数是简单的虚拟函数,用于说明其用途。请不要自己想出更好的方法来实现这些功能。

方法一
def fun_a(n):
    for i in range(n):
        yield i+10

def fun_b(n):
    if n < 0: 
        yield None
        return
    yield fun_a(n)

并将其用作 list(list(fun_b(10))[0]) 以获得 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

方法二
def fun_b(n):
    if n < 0: 
        yield None
        return
    for i in fun_a(n):
        yield i

list(fun_b(10))可以给我[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

虽然方法 1 似乎没问题,但我不想 return 列表的列表,因为在其他情况下我正在 return 列表,我不想弄乱上我的代码。方法2效率低下。

处理这种情况的真正好方法是什么?

如果您使用的是 Python 3.3 或更高版本,您可以使用 PEP 380 中引入的 yield from 语法:

PEP 380 adds the yield from expression, allowing a generator to delegate part of its operations to another generator. This allows a section of code containing yield to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.

>>> def fun_a(n):
    for i in range(n):
        yield i+10

>>> def fun_b(n):
    if n < 0: 
        yield None
        return
    yield from fun_a(n)


>>> list(fun_b(10))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> 

如果没有,那么您只需要使用 for item in iterable: 语法。