为什么我的Python函数只运行一次?

时间:2015-03-23 04:33:06

标签: python long-integer

我目前正在进行一项任务,我必须分析一个pickle文件,这个文件基本上是一个巨大的列表列表(36,600个列表,每个列表都列出了波士顿,芝加哥,洛杉矶特定日期的温度,达拉斯或丹佛)。

列表'格式是:

[city, month, day, year, temperature (on this specific date) ]

所以在导入pickle并打开这个文件后,我做了:

import pickle
weather_file = open("Weather Data.pkl","rb")
obj1 = pickle.load(weather_file)
import statistics

例如,obj [30000]会打印:

['Los Angeles', 11, 27, 1996, 65.8]
然后我做了

LA_temp = list()
for D in obj1:
    if D[0] == "Los Angeles" and D[1] == 1 and D[3] == 2014:
        LA_temp.append(D[4])

LA_temp成为一个包含31个要素的清单,这些要素是2014年1月31天的温度。

55.6, 60.7, 57.2, 56.4, 59.1, 63.5, 61.1, 57.2, 56.2, 56.3, 57.4, 57.9, 62.7, 66.2, 67.8, 68.6, 69.5, 65.9, 61.2, 60.7, 61.8, 63.0, 57.7, 61.9, 63.9, 59.9, 60.6, 57.6, 57.4, 56.1, 58.7]

但是,我决定将此代码放在一个函数中:

def LA_monthly_temp (month):
    LA_temp = list()
    for D in obj1:
       if D[0] == "Los Angeles" and D[1] == month and D[3] == 2014:
           LA_temp.append(D[4])
           return (statistics.mean(LA_temp))

理想情况下,此功能应返回2014年1月洛杉矶的温度平均值。但是,此功能仅将2014年1月第一天的温度添加到列表中,然后停止。

具体地

LA_monthly_temp(1)

会产生" 55.6"而不是" 60.7"这是正确的答案。

为什么我的函数只运行一次,即使我的代码完全相同?

1 个答案:

答案 0 :(得分:4)

return语句的缩进是错误的。 它需要以与for D in obj1:

相同的方式缩进
def LA_monthly_temp (month):
    LA_temp = list()
    for D in obj1:
        if D[0] == "Los Angeles" and D[1] == month and D[3] == 2014:
            LA_temp.append(D[4])
    return (statistics.mean(LA_temp))

这样,return发生在整个循环之后。在您的情况下,return在读取第一个项目后发生。

相关问题