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

时间:2015-11-30 16:37:56

标签: python python-2.7 generator yield

我知道如何在python中使用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

但我有这样的代码

{{1}}

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

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

1 个答案:

答案 0 :(得分:2)

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

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