计算并返回列表中的平均值 [英] Calculate and return average values in a list

查看:438
本文介绍了计算并返回列表中的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一长串列出了一些值.我想定义一个函数,该函数接受列表并计算列表中每24个值的平均值,然后将平均值作为列表返回.我该怎么做呢?我的列表中有8760个元素,返回的列表应为8760/24 = 365个元素.

I have a long list with some values. I want to define a function that take the list and calculates the average for every 24 values in the list, and returns the average values as a list. How do I do this? I have 8760 elements in the list, and the list returned should give 8760/24=365 elements.

hourly_temp = ['-0.8', '-0.7', '-0.3', '-0.3', '-0.8',
'-0.5', '-0.7', '-0.6', '-0.7', '-1.2', '-1.7...] #This goes on, it's 8760 elements

def daily_mean_temp(hourly_temp):

    first_24_elements = hourly_temp[:24] #First 24 elements in the list

这是正确的吗?我收到一条错误消息:TypeError:无法使用灵活类型执行reduce

Is this correct? I get an error saying: TypeError: cannot perform reduce with flexible type

def daily_mean_temp(hourly_temp):
averages = [float(sum(myrange))/len(myrange) 
        for myrange in zip(*[iter(hourly_temp)]*24)]
return averages

推荐答案

假设您想要独立的组,则可以使用grouper

Assuming that you want independent groups, you can use the grouper itertools recipe:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

然后轻松获得每个group的平均值:

And then easily get the average of each group:

averages = [sum(group)/float(len(group)) for group in grouper(data, 24)]


编辑:鉴于您的数据似乎是字符串列表,我建议您首先使用


Edit: given that your data appears to be a list of strings, I would suggest you convert to floats first using map:

data = map(float, hourly_temp)

这篇关于计算并返回列表中的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆