是否存在“让发电机产生所有输出"的简写形式? [英] Is there any shorthand for 'yield all the output from a generator'?
本文介绍了是否存在“让发电机产生所有输出"的简写形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否存在用于以下内容的单行表达式:
Is there a one-line expression for:
for thing in generator:
yield thing
我尝试yield generator
无济于事.
推荐答案
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]
不幸的是,Python 2.7没有等效的结构:'(
Unfortunately, Python 2.7 has no equivalent construct :'(
这篇关于是否存在“让发电机产生所有输出"的简写形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文