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

南楼画角 提交于 2020-05-28 12:04:13

问题


Is there a one-line expression for:

for thing in generator:
    yield thing

I tried yield generator to no avail.


回答1:


In Python 3.3+, you can use yield from. For example,

>>> 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]

It can actually be used with any iterable. For example,

>>> 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]

Unfortunately, Python 2.7 has no equivalent construct :'(




回答2:


You can use a list comprehension to get all of the elements out of a generator (assuming the generator ends):

[x for x in generator]



回答3:


Here is a simple one-liner valid in Python 2.5+ as requested ;-):

for thing in generator: yield thing


来源:https://stackoverflow.com/questions/29445597/is-there-any-shorthand-for-yield-all-the-output-from-a-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!