【问题标题】:python generator expression from generator , is it possible? [duplicate]来自 generator 的 python 生成器表达式,有可能吗? [复制]
【发布时间】:2013-12-16 17:46:57
【问题描述】:

我正在尝试转换我的功能,我希望它做同样的事情:

    def get_num(function, starting_index):
        yield starting_index
        while True:
            yield function(starting_index)
            starting_index = function(starting_index)

所以我希望新函数返回一个完全相同的 genexp,当然不使用“yield”,并且全部在一行中,这可能吗? 谢谢

【问题讨论】:

  • 为什么要这样做?恕我直言,这看起来比等效的生成器表达式要好得多。
  • 一半功课,一半自学,我不一定需要代码,想法,或者事情的开始也很好!
  • @TimPeters 我的“最爱”是this one
  • 这是什么糟糕的作业?!它不会教你如何编程,而是教你如何使用 Stack Overflow 找到可怕地滥用它所设置的任何语言的方法。

标签: python


【解决方案1】:

首先,您可能希望避免对函数的冗余调用:

def get_num(fn, start):
    while True:
        yield start
        start = fn(start)

【讨论】:

  • 谢谢,但不是我问的
【解决方案2】:

原始函数的递归版本:

def get_num(f, x):
    yield x
    yield from get_num(f, f(x))

同一主题:

>>> p = lambda x, f, c: chain((x,), (i for i in p(f(x), f, c))) if c(x) else (x, None)
>>> p(1, lambda x: x*2, lambda x: x < 100)
<itertools.chain object at 0x01633DD0>
>>> list(_)
[1, 2, 4, 8, 16, 32, 64, 128, None]

这与原始函数的作用相同,但如果 x 满足某些条件则停止。

那是因为它必须是生成器表达式?!我们这样做:

>>> g = (i for i in _)
>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
>>> next(g)
16

条件函数c 是停止无限递归所必需的。如果 Python 更像是一种函数式语言(即惰性求值更常见,并且尾递归得到优化),那么这将没有必要。

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 2017-12-08
    • 2012-02-10
    • 2014-04-02
    • 2021-12-27
    • 2020-07-08
    • 2021-03-19
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多