如何在 Python 中查找列表的平均值
Python 平均值
Python 平均值函数用于查找列表中给定数字的平均值。Python 中计算平均值的公式是将列表中数字的总和除以列表中数字的数量。
Python 列表的平均值可以通过多种方式完成,如下所示:
方法 1:通过循环计算 Python 平均值
在此示例中,我们将变量 sum_num 初始化为零并使用了 for 循环。该 for 循环将遍历列表中的元素,每个数字都会被加到 sum_num 变量中并保存。Python 列表的平均值是通过使用 sum_num
除以列表中数字的数量(使用 len()
内置函数)来计算的。
代码示例
def cal_average(num): sum_num = 0 for t in num: sum_num = sum_num + t avg = sum_num / len(num) return avg print("The average is", cal_average([18,25,3,41,5]))
输出
The average is 18.4
方法 2:Python 平均值 – 使用 sum() 和 len() 内置函数
在此示例中,使用 sum()
和 len()
内置函数来查找 Python 中的平均值。这是一种直接计算平均值的方法,因为您不必遍历元素,而且代码量也减少了。如以下所示,平均值可以用一行代码计算。
程序示例
# Example to find average of list number_list = [45, 34, 10, 36, 12, 6, 80] avg = sum(number_list)/len(number_list) print("The average is ", round(avg,2))
输出
The average is 31.86
方法 3:使用 statistics 模块中的 mean 函数计算 Python 平均值
您可以使用 statistics 模块中的 mean 函数轻松计算“平均值”。下面是示例
# Example to find the average of the list from statistics import mean number_list = [45, 34, 10, 36, 12, 6, 80] avg = mean(number_list) print("The average is ", round(avg,2))
输出
The average is 31.86
方法 4:使用 numpy 库中的 mean() 计算 Python 平均值
Numpy 库是处理大型多维数组常用的库。它还包含大量数学函数,可用于数组以执行各种任务。其中一个重要的函数是 mean()
函数,它将为给定的列表提供平均值。
代码示例
# Example to find avearge of list from numpy import mean number_list = [45, 34, 10, 36, 12, 6, 80] avg = mean(number_list) print("The average is ", round(avg,2))
输出
C:\pythontest>python testavg.py The average is 31.86
摘要
- 计算平均值的公式是将列表中数字的总和除以列表中数字的数量。
- 列表的平均值可以通过多种方式完成,即:
- 使用循环计算 Python 平均值
- 使用 Python 的
sum()
和len()
内置函数 - 使用
mean()
函数从 statistics 模块计算平均值。 - 使用 numpy 库中的
mean()