使用到目前为止构建的列表将代码转换为生成器

Converting code using list built so far, to a generator

我知道 yield 关键字是如何在 python 到 return 生成器中使用的,像这样

def example_function():
    for i in xrange(1, 10)
        yield i

但是我有这样的代码

def feed_forward(self,inputs):
    activations = [inputs]
    for I in xrange(len(self.weights)):
        activation = activations[i].dot(self.weights[i])
        activations.append(activation)
    return activations

要创建的列表本身在函数内部的迭代中是必需的。

如何使用 yield 关键字将代码重写为更多 pythonic 代码?

yield 语句替换.append() 调用和初始列表定义。您每次在循环的下一次迭代中都使用前面的结果,只需记录最后一个 'activation' 并重新使用它:

def feed_forward(self, inputs):
    yield inputs
    activation = inputs
    for weight in self.weights:
        activation = activation.dot(weight)
        yield activation