Python 使用迄今为止构建的列表将代码转换为生成器

Python 使用迄今为止构建的列表将代码转换为生成器,python,python-2.7,generator,yield,Python,Python 2.7,Generator,Yield,我知道python中如何使用yield关键字来返回生成器 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]

我知道python中如何使用
yield
关键字来返回生成器

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
但我有这样的代码

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()
调用和初始列表定义。在循环的下一次迭代中,每次都使用前面的结果,只需记录最后一次“激活”并重复使用:

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

@高谭:啊,当然。这是之前的值,真的。我会纠正的。有可能以相反的顺序返回发电机吗?@Goutam:没有;生成器是编写迭代器的一种方式,迭代器是单向的。唯一的选择是捕获列表中的所有输出,然后反转列表。这样做是pythonic吗?@Goutam:你想解决什么问题?你能不能不按相反的顺序产生结果?