首页 > 解决方案 > 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

我有地图、过滤器等。我想被屈服,有没有其他方法可以做到?我看了看itertoolsfunctools我什么也找不到。

编辑:

更清楚地说,我想要一种在每个函数调用时返回一个值的方法。

标签: pythonpython-3.xgeneratoryield

解决方案


尝试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

推荐阅读