简体   繁体   English

如何计算python中列表元素的平均值?

[英]How to calculate average values of list elements in python?

I'd like to calculate average of each values in a list.我想计算列表中每个值的平均值。 To do so, I wrote a function which gets list as parameter and calculate the average and returns the list of average again.为此,我编写了一个函数,它将列表作为参数并计算平均值并再次返回平均值列表。

Here is the signal:这是信号:

random_data = [10 * random.uniform(0,1) for i in range(1000)]
random_peak = [100 * random.uniform(0,1) for i in range(50)] + [0] * 950
random.shuffle(peak)
for i in range(0, len(signal)):
    signal = [peak[x] + random_data[x] for x in range(len(random_data))]

And now, I'd like to calculate m as following.现在,我想计算 m 如下。

'''
m1 = 1/(number of signal) * x1
m2 = 1/(number of signal) * (x1+x2)
m3 = 1/(number of signal) * (x1+x2+x3)
...
'''

I wrote a following function to calculate m.我编写了以下函数来计算 m。 How would I change the function to return list of ms?我将如何更改函数以返回 ms 列表?

def mean_values(s):
    for i in range(len(s)):
        m[i] = 1/len(s)*s[i]
    return m[i]

mean_values(signal)
#mean_values(np.array(signal)

use m as a float instead of list it make more sense to get mean使用 m 作为浮点数而不是列表更有意义

s = 1 / n * Σxi

you can use this to get new mean from a previous one您可以使用它从以前的平均值中获得新的平均值

s' = s + (x1 - s) / n1

where s is the lastest mean, x1 the new value and n1 the new length However in numpy their is a prebuilt function np.mean() which do that and manage python list too其中 s 是最新的平均值,x1 是新值,n1 是新长度 但是在 numpy 中,它们是一个预构建的函数 np.mean() ,它可以执行此操作并管理 python 列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM