如何在Python中计算平均数

964 阅读6分钟

Python Statistics Module Tutorial With Example

Python中的统计模块提供了计算数字(Real-value)数据统计的函数。算术平均值是数据之和除以数据点的数量。它衡量数据在一组范围不同的数值中的中心位置。

Python 3统计模块提供了方便的函数,如平均数中位数模式等。

Python平均数

mean()是一个内置的Python统计函数,用于计算 数字列表平均值mean()函数接受数据作为参数,并返回 数据平均值 。要在Python程序中使用**mean()**方法,请导入 Python统计模块,然后我们可以使用 mean 函数来返回给定列表的平均值。请看下面的例子。

让我们看看统计模块的一些例子。

# app.py

import statistics

data = [11, 21, 11, 19, 46, 21, 19, 29, 21, 18, 3, 11, 11]

x = statistics.mean(data)
print(x)

y = statistics.median(data)
print(y)

z = statistics.mode(data)
print(z)

a = statistics.stdev(data)
print(a)

b = statistics.variance(data)
print(b)

请看下面的输出。

➜  pyt python3 app.py
18.53846153846154
19
11
10.611435534486562
112.6025641025641
➜  pyt

在上面的代码例子中,我们使用了 Mean,mode,median,variance,stddev函数。

Python 列表的平均数

要在Python中计算列表的平均值或平均数:

  1. 使用 statistics.mean() 函数。
  2. 使用 sum() 和 len() 函数。
  3. 使用Python numpy.mean()。

计算平均数的公式是通过计算列表中数字的总和除以列表中数字的数量来实现的。

# app.py

import statistics

spiList = [5.55, 5.72, 7.3, 7.75, 8.4, 9, 8.8, 8.2]
print(statistics.mean(spiList))

请看下面的输出。

Python mean Function Example

在上面的例子中,我们有8个数据点,使用statistics.mean()函数,我们计算出了列表的平均值。

使用For循环来计算平均值

在下面的代码例子中,我们将变量sumOfNumbers 初始化为0,并使用for循环。Python for 循环将循环浏览列表中的元素,每个数字都被添加并保存在 sumOfNumbers 变量 中 。

使用len()内置函数,用sumOfNumbers除以列表中的数字数来计算平均值。

请看下面的代码。

# app.py

def averageOfList(num):
    sumOfNumbers = 0
    for t in num:
        sumOfNumbers = sumOfNumbers + t

    avg = sumOfNumbers / len(num)
    return avg


print("The average of List is", averageOfList([19, 21, 46, 11, 18]))

输出

python3 app.py
The average of List is 23.0

在上面的代码中,我们使用for循环来计算所有项目的总和,然后用这个总和除以几个项目来得到Python中的平均值。

使用 sum() 和 len() 函数

Python的sum()是一个内置函数,返回所有列表元素的总和。同样,Python len()函数给出了列表中的项目数。我们将使用这两个内置函数的组合来获得列表的平均值。

请看下面的代码。

# app.py

def averageOfList(numOfList):
    avg = sum(numOfList) / len(numOfList)
    return avg


print("The average of List is", round(averageOfList([19, 21, 46, 11, 18]), 2))

输出

python3 app.py
The average of List is 23.0

使用numpy.mean()函数

NumPy.mean()函数返回数组元素的平均值。默认情况下,平均数取自扁平化的数组,否则取自指定的轴。

Numpy库是一个常用的库,用于处理大型多维数组。它也有大量关于数组的数学函数集合,以执行各种任务。这里需要注意的一件事是,mean()函数会给我们提供列表的平均值。

请看下面的代码。

# app.py

from numpy import mean
number_list = [19, 21, 46, 11, 18]
avg = mean(number_list)
print("The average of List is ", round(avg, 2))

输出

python3 app.py
The average of List is 23.0

更多例子

首先,我们将导入统计模块,然后调用mean()函数来获得数据的平均值。

# app.py

import statistics

data = [21, 19, 18, 46, 30]
print(statistics.mean(data))

请看下面的输出。

Python Statistics Tutorial | mean Function Example

在Python中计算一个元组的平均数。

要在 Python 中找到一个元组的平均数,使用 statistics.mean() 方法与我们找到列表的平均数一样。我们必须把元组作为一个参数传递。 让我们用下面的代码来计算元组的平均数。

# app.py

import statistics

tupleA = (1, 9, 2, 1, 1, 8)
print(statistics.mean(tupleA))

上述代码的输出如下。

Calculate Mean of a tuple

它的工作原理与列表相同。它只是返回元组内数字的平均值

在 Python 中计算 Dictionary 的平均数

要计算 Dictionary 的平均值,我们可以使用 statistics.mean() 方法。 在 Dictionary 中,mean 函数只对键值进行计数,并根据字典的键值返回该 Dictionary 的平均值。

# app.py

import statistics

dictA = {1: 19, 2:21, 3:18, 4:46, 5:30}
print(statistics.mean(dictA))

请看下面的输出。

Calculate Mean of a Dictionary

计算一个负数集的元组的平均数

我们用统计学的方法来寻找负数集的元组的平均数.mean()。我们需要将负数元组作为参数传递给mean()函数,作为回报,我们将得到输出。

让我们来看看这个负整数的元组。

# app.py

import statistics

data = (-11, -21, -18, -19, -46)
print(statistics.mean(data))


请看下面的输出。

➜  pyt python3 app.py
-23
➜  pyt

让我们以混合范围的数字的元组为例。

# app.py

import statistics

data = (11, 21, -18, 19, -46)
print(statistics.mean(data))

请看下面的输出。

➜  pyt python3 app.py
-2.6
➜  pyt

计算负数组的列表的平均数

要在 Python 中计算列表的平均值,请使用 statistics.mean() 方法。我们将把负数集的列表传递给 mean() 方法,在输出中,我们将计算出平均值。

让我们取一个负整数的列表并应用mean() 函数

# app.py

import statistics

data = [-11, -21, -18, -19, -46]
print(statistics.mean(data))


请看下面的输出。

➜  pyt python3 app.py
-23
➜  pyt

让我们以一个混合范围的数字列表为例。

# app.py
import statistics

data = [11, 21, -18, -19, 46]
print(statistics.mean(data))

请看输出结果。

➜  pyt python3 app.py
8.2
➜  pyt

如何计算分数列表的平均数

要计算分数列表的平均数,请使用 statistics.mean() 方法。首先,我们必须导入统计和分数模块,然后创建一个分数的数字,在输出中,我们将得到均值。

# app.py

import statistics
from fractions import Fraction as fr

data = [fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3)]

print(statistics.mean(data))

请看下面的输出。

➜  pyt python3 app.py
49/24
➜  pyt


Python中的TypeError

让我们在Python字典中采取字符串键,并得到字符串值的平均值。它将得到错误,因为我们找不到字符串的平均值。

请看下面的代码。

# app.py

import statistics

data = {"a": 11, "b": 21, "c": 19,
        "d": 29, "e": 18, "f": 46}

print(statistics.mean(data))


请看下面的输出。

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 6, in 
    print(statistics.mean(data))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/statistics.py", line 312, in mean
    T, total, count = _sum(data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/statistics.py", line 148, in _sum
    for n,d in map(_exact_ratio, values):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/statistics.py", line 230, in _exact_ratio
    raise TypeError(msg.format(type(x).__name__))
TypeError: can't convert type 'str' to numerator/denominator
➜  pyt

结论

要在Python中找到List的平均值或平均数,我们可以使用以下方法。

  1. 使用 statistics.mean() 方法。
  2. 使用Python sum()和 len() 方法。
  3. 使用Numpy.mean()函数。
  4. 使用Python for loop和len()方法。

最后,Python mean()函数示例结束。