添加多个功能的结果

时间:2014-04-20 05:10:58

标签: function python-3.x mapping

使用python 3.3

我的程序偶然发现了另一个问题。它的太阳能计划相同。我再次决定添加更多功能。它基本上是临时的。随着我的进展,我会添加一些东西。我意识到它可以提高效率,但一旦我决定完成它,我就会发布整个编码。

无论如何,我需要添加多个功能的结果。这是我编码的一部分:

def janCalc():
    for a in angle(0,360,10):                                           #angle of orientation
        for d in days(1,32,1.0006630137):                               #day number of year
            for smodule in equation():                  #equation() function not shown in this coding
                total_jan+=smodule              #total_jan is already defined elsewhere              
        avg_jan=total_jan/(60*(1.0006630137*31))                
        ratio_jan=avg_jan/5.67
        calcJan=(ratio_jan*4.79)
        yield calcJan
        total_jan=0                     #necessary to reset total to 0 for next angle interval    

def febCalc():
    for a in angle(0,360,10):
        for d in days ((1.0006630137*31),61,1.0006630137):
            for smodule in equation():
                total_feb+=smodule
        avg_feb=total_feb/(60*(1.0006630137*28))
        ratio_feb=avg_feb/6.56
        calcFeb=(ratio_feb*4.96)
        yield calcFeb
        total_feb=0

#etc..............

无论如何都要添加每个函数的收益? 例如:calcJan + calcFeb + .....

我想得到每个角度间隔下的总结果,然后除以12得到每个区间的平均值。像这样: -

0度---->总计/ 12

10度---->总/ 12

20度---->总/ 12

30度---->总/ 12

........

360度---->总计/ 12

如果您需要更多信息,请与我们联系。

附录

解决方案基本上由@jonrsharpe解决。但我遇到了一些问题。

Traceback (most recent call last):
  File "C:\Users\User\Documents\Python\Solar program final.py", line 247, in <module>
    output=[sum(vals)/12 for vals in zip(*(gen() for gen in months))]
  File "C:\Users\User\Documents\Python\Solar program final.py", line 247, in <listcomp>
    output=[sum(vals)/12 for vals in zip(*(gen() for gen in months))]
  File "C:\Users\User\Documents\Python\Solar program final.py", line 103, in janCalc
    for smodule in equation():
  File "C:\Users\User\Documents\Python\Solar program final.py", line 63, in equation
    d=math.asin(math.sin(math.radians(23.45))*math.sin(math.radians((360/365.242)*(d-81))))
NameError: global name 'd' is not defined

我已将其隔离到:

for d in days ((1.0006630137*31),61,1.0006630137):    
    for smodule in equation(): 

事实证明我无法从函数内部引用函数?我不太确定。所以即使我原来的编码也行不通。我认为这是有效的,因为以前我没有将每个月定义为一个函数。我应该先测试一下。

你知道怎么解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

演示如何组合多个生成器的简单示例:

>>> def gen1():
    for x in range(5):
        yield x

>>> def gen2():
    for x in range(5, 10):
        yield x

>>> [sum(vals) for vals in zip(*(gen() for gen in (gen1, gen2)))]
[5, 7, 9, 11, 13]

或者,写出来的长手:

output = list(gen1())
for index, value in enumerate(gen2()):
    output[index] += value

您也可以修改任一版本以包含分部,因此您的案例应如下所示:

months = [janCalc, fabCalc, ...]

output = [sum(vals) / 12 for vals i zip(*(gen() for gen in months))]