'yield all the output from a generator'有没有shorthand?

Is there any shorthand for 'yield all the output from a generator'?

是否有单行表达式:

for thing in generator:
    yield thing

我试过yield generator没用。

在Python 3.3+中,可以使用yield from。例如,

>>> def get_squares():
...     yield from (num ** 2 for num in range(10))
... 
>>> list(get_squares())
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

它实际上可以与任何可迭代对象一起使用。例如,

>>> def get_numbers():
...     yield from range(10)
... 
>>> list(get_numbers())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def get_squares():
...     yield from [num ** 2 for num in range(10)]
... 
>>> list(get_squares())
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

不幸的是,Python 2.7 没有等效的结构 :'(

您可以使用列表理解从生成器中获取所有元素(假设生成器结束):

[x for x in generator]

这是根据要求在 Python 2.5+ 中有效的简单单行代码 ;-):

for thing in generator: yield thing