python - Python,从生成器产生的紧凑方法
问题描述
我有一台发电机,我想得到它。
def foo():
a = map(lambda x: x*2, range(5))
# I want a better way to the next few lines
# The one that looks more functional
for i in a:
yield i
我有地图、过滤器等。我想被屈服,有没有其他方法可以做到?我看了看itertools
,functools
我什么也找不到。
编辑:
更清楚地说,我想要一种在每个函数调用时返回一个值的方法。
解决方案
尝试yield from
(python 版本必须 >= 3.3);
def foo():
a = map(lambda x: x*2, range(5))
yield from a
或任何版本,可以使用iter
:
def foo():
a = map(lambda x: x*2, range(5))
return iter(a)
iter
相当于生成器:
(i for i in seq)
完整示例:
def foo():
a = map(lambda x: x*2, range(5))
return (i for i in a)
更新:
a = iter(map(lambda x: x*2, range(5)))
def foo():
return next(a)
print(foo())
print(foo())
输出:
0
2
顺便说一句,在这种情况下它是 a map
,所以不需要iter
:
a = map(lambda x: x*2, range(5))
def foo():
return next(a)
print(foo())
print(foo())
输出:
0
2
推荐阅读
- python - 处理 Django Util Timezone Ambiguous Time Error 而不直接修改 Django 包
- php - PHP Form Mail不发送电子邮件,给出一个空白页面,没有错误消息
- javascript - 如何使用 Javascript 在 CSS 中动态设置背景图片 url
- c# - 什么是 dropdownlist.selectedvalue?
- python - 如何从具有重复数据块的大文件中提取多个模式?
- bash - 来自 bash CLI 的 InfluxDB 查询
- flutter - [flutter]我无法在 Paint 中使用 BlendMode.srcIn
- matrix - 如何使用 sympy 执行向量乘法矩阵?
- python - Python 请求库无法解析非权威的 dns 查找
- fiware - Fiware orion 订阅发送空体