Wal*_*Cat 15 python yield generator python-2.7
是否有单行表达式:
for thing in generator:
yield thing
Run Code Online (Sandbox Code Playgroud)
我试着yield generator无济于事.
the*_*eye 16
在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]
Run Code Online (Sandbox Code Playgroud)
它实际上可以与任何可迭代使用.例如,
>>> 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]
Run Code Online (Sandbox Code Playgroud)
不幸的是,Python 2.7没有等效的构造:'(
您可以使用列表推导将所有元素从生成器中取出(假设生成器结束):
[x for x in generator]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3678 次 |
| 最近记录: |