如何将生成器yield语句传递给另一个函数 -Python
我在这个网站上看了很多内容,但就是找不到我想要的具体答案。我试着阅读David Beasley关于迭代和生成器的幻灯片,但还是没能找到我想要的答案,尽管问题看起来很简单。我正在运行一个基于时钟的模拟(用于神经网络的Brian),我有一个生成器,它在处理输出并将它们加到一个运行的总和中(这样可以实现简单低通滤波器的指数衰减)。然后,我想在每个时间步取这些生成器的输出,并在另一个函数中使用它们来更新一些状态变量,但系统提示我由于这个项目是生成器类型,我不能这样做。代码和代码解释如下:
import numpy
our_range=numpy.arange(0*ms,duration+defaultclock.dt,defaultclock.dt)
a=our_range
c=defaultclock.t #this is a clock that is part of the program i'm running, it updates every #timestep and runs through the range given above
def sum_tau(neuron): #this gives a running sum which i want to access (the alphas can be ignored as they are problem specific)
for c in a: #had to express it like this (with c and a) or it wouldn't run
if c ==0:
x=0
elif defaultclock.still_running()==False:
return
else:
x = x*(1-alpha) + p(neuron)*alpha
print x
yield x
#p(neuron) just takes some of the neurons variables and gives a number
b=sum_tau(DN) #this is just to specify the neuron we're working on, problem specific
@network_operation
def x():
b.next()
这里的@network_operation意味着每个时钟时间步都会执行下面的函数,从而更新总和到所需的值。现在我想做的是更新一个用于模拟的值(其中d是另一个生成器的输出,虽然没有显示,但和b非常相似),我输入:
ron= (d/(1-b))
但是,它说我不能以这种方式使用生成器对象。我使用打印语句来确认b(和d)在每个时间步(当模拟运行时)都给出了我想要的输出,但我似乎无法拿这些输出做任何事情。(更具体地说,是不支持的操作数类型'-',因为int和generator不能相减。我尝试用float()将其转换为数字,但显然这也不行,原因和之前一样。我觉得我的问题应该有一个非常简单的解决方案,但我就是找不到。提前谢谢你。
1 个回答
更具体地说,"不支持的操作数类型 '-',用于 int 和生成器" 这句话给了你一个提示。
你不能在简单的公式中直接使用生成器。你需要用生成器表达式来“展开”它。
ron= (d/(1-b))
你有一个生成器 b
,对吧?b
不是一个“值”。它是一种值的序列。
所以,你需要把序列中的每个值都应用到你的公式中。
ron = [ d/(1-x) for x in b ]
这样就能获取序列中的每个值,并计算出一个新的值。
(不太清楚这样做是否真的有用,因为当 b
是一组值时,原来的 ron= (d/(1-b))
其实并没有太大意义。)