在Python中计算算术平均值(一种平均值)

2020/10/31 18:52 · python ·  · 0评论

Python中是否有内置或标准库方法来计算数字列表的算术平均值(一种平均值)?

我不知道标准库中的任何内容。但是,您可以使用类似以下内容的方法:

def mean(numbers):
    return float(sum(numbers)) / max(len(numbers), 1)

>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0

在numpy中,有numpy.mean()

NumPy的anumpy.mean是算术平均值。用法很简单:

>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335

用途statistics.mean

import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

自Python 3.4起可用。对于3.1-3.3用户,该模块的旧版本可在PyPI上以的名称获得stats只需更改statistics为即可stats

您甚至不需要麻木或肮脏的...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3

使用scipy:

import scipy;
a=[1,2,4];
print(scipy.mean(a));

除了强制浮动之外,您还可以执行以下操作

def mean(nums):
    return sum(nums, 0.0) / len(nums)

或使用lambda

mean = lambda nums: sum(nums, 0.0) / len(nums)

更新日期:2019-12-15

Python 3.8统计模块中添加了功能fmean哪个更快,并且总是返回float。

将数据转换为浮点并计算算术平均值。

它的运行速度比mean()函数快,并且始终返回浮点数。数据可以是序列或可迭代的。如果输入数据集为空,则引发StatisticsError。

fmean([3.5,4.0,5.25])

4.25

3.8版的新功能。

from statistics import mean
avarage=mean(your_list)

例如

from statistics import mean

my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)

结果是

3.0
def avg(l):
    """uses floating-point division."""
    return sum(l) / float(len(l))

例子:

l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]

print(avg(l1)) # 9.0
print(avg(l2)) # 0.0
def list_mean(nums):
    sumof = 0
    num_of = len(nums)
    mean = 0
    for i in nums:
        sumof += i
    mean = sumof / num_of
    return float(mean)

我一直认为avg内置/ stdlib中会省略它,因为它很简单

sum(L)/len(L) # L is some list

并且任何告诫将在调用者代码中解决以供本地使用

注意事项:

  1. 非浮点结果:在python2中,9/4为2。解析,使用float(sum(L))/len(L)from __future__ import division

  2. 除以零:列表可能为空。解决:

    if not L:
        raise WhateverYouWantError("foo")
    avg = float(sum(L))/len(L)
    

The proper answer to your question is to use statistics.mean. But for fun, here is a version of mean that does not use the len() function, so it (like statistics.mean) can be used on generators, which do not support len():

from functools import reduce
from operator import truediv
def ave(seq):
    return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]), 
                           enumerate(seq, start=1), 
                           (0, 0)))

Others already posted very good answers, but some people might still be looking for a classic way to find Mean(avg), so here I post this (code tested in Python 3.6):

def meanmanual(listt):

mean = 0
lsum = 0
lenoflist = len(listt)

for i in listt:
    lsum += i

mean = lsum / lenoflist
return float(mean)

a = [1, 2, 3, 4, 5, 6]
meanmanual(a)

Answer: 3.5
本文地址:http://python.askforanswer.com/zaipythonzhongjisuansuanshupingjunzhiyizhongpingjunzhi.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!