【问题标题】:Python, compact way to yield from a generator [duplicate]Python,从生成器产生的紧凑方法[重复]
【发布时间】:2019-02-19 03:08:35
【问题描述】:

我有一个生成器,我希望得到它。

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,找不到任何东西。

编辑:

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

【问题讨论】:

  • 在文档中搜索yield from
  • yield from a 也许?
  • 地图对象不是生成器(也缺少)
  • 链接问题中得分最高的答案包含有关yield fromstackoverflow.com/a/18620655/4014959的良好信息
  • 顺便说一句,我认为这只是一个玩具示例,但使用 lambda 作为 map 的函数 arg 是一种代码味道。改为写一个生成表达式。这样您就可以避免每次迭代都调用缓慢的 Python 函数。

标签: python python-3.x generator yield


【解决方案1】:

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

顺便说一下,在这种情况下它是map,所以不需要iter

a = map(lambda x: x*2, range(5))
def foo():
    return next(a)

print(foo())
print(foo())

输出:

0
2

【讨论】:

  • 所有这些都返回整个生成器,我正在寻找一个在每个函数调用中一次返回一个值的生成器。
  • @VasanthaGaneshK 编辑了我的
  • 我现在明白任何一种方式都是一样的。谢谢!
  • @VasanthaGaneshK 如果可行,请接受
  • @VasanthaGaneshK 很高兴我提供了帮助,?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多