首页 > 编程知识 正文

Python 中列表的平均值

时间:2023-11-26 13:13:11 阅读:309362 作者:NSAH

在本教程中,我们将讨论如何用 Python 计算列表的平均值。

列表的平均值定义为列表中存在的元素之和除以列表中存在的元素数量。

在这里,我们将使用三种不同的方法来使用 Python 计算列表中元素的平均值。

  1. 使用求和()
  2. 使用减少()
  3. 使用平均值()

所以,让我们开始吧…

使用总和()

在第一种方法中,我们使用 sum()和 len()来计算平均值。

下面的程序说明了同样的情况-


# Python program to get average of a list
def calc_average(lst):
    return sum(lst) / len(lst)
lst = [24, 19, 35, 46, 75, 29, 30, 18]
average = calc_average(lst)
# Printing the average value of the list
print("The average of the list is ", round(average, 3))

输出:

The average of the list is  34.5

解释-

是时候看看我们在上面的程序中做了什么-

  1. 在第一步中,我们创建了一个函数,该函数以列表为参数,然后使用 sum() 和 len()返回平均值。我们知道 sum() 用来计算元素的和,len()告诉我们列表的长度。
  2. 在这之后,我们已经初始化了列表,我们想要计算它的平均值。
  3. 在下一步中,我们将这个列表作为参数传递给我们的函数。
  4. 最后,我们打印结果值。

在下一期节目中,我们将看到 reduce() 如何帮助我们做同样的事情。

使用 reduce()

下面给出的程序展示了如何做到这一点-


# Python program to obtain the average of a list
# Using reduce() and lambda
from functools import reduce
def calc_average(lst):
    return reduce(lambda a, b: a + b, lst) / len(lst)
#initializing the list
lst = [24, 19, 35, 46, 75, 29, 30, 18]
average = calc_average(lst)
# Printing average of the list
print("The Average of the list is ", round(average, 2))

输出:

The average of the list is  34.5

解释

让我们了解我们在这里做了什么-

  1. 在第一步中,我们从 functools 导入了 reduce,这样我们就可以在程序中使用它来计算元素的平均值。
  2. 现在,我们已经创建了一个函数 calc_average,它以一个列表作为参数,并在 reduce 内部使用 lambda(python 中编写函数的一种精确方式)来计算平均值。
  3. 在此之后,我们已经初始化了我们想要计算的平均值。
  4. 在下一步中,我们将这个列表作为参数传递给我们的函数。
  5. 最后,我们打印结果值。

在上一个程序中,我们将学习如何使用 mean() 来计算列表的平均值

使用平均值()

下面的程序展示了如何做到这一点


# Python program to obtain the average of a list
# Using mean()
from statistics import mean
def calc_average(lst):
    return mean(lst)
lst = [24, 19, 35, 46, 75, 29, 30, 18]
average = calc_average(lst)
# Printing the average of the list
print("The average of the list is ", round(average, 2))

输出:

The average of the list is  34.5

解释-

是时候看看我们在上面的程序中做了什么-

  1. 第一步,我们从统计数据中导入平均值,这样我们就可以在程序中使用它来计算元素的平均值。
  2. 现在,我们已经创建了一个函数 calc_average,它以列表为参数,使用 mean() 计算平均值。
  3. 在此之后,我们已经初始化了我们想要计算的平均值。
  4. 在下一步中,我们将这个列表作为参数传递给我们的函数。
  5. 最后,我们打印结果值。

结论

在本教程中,我们学习了使用 Python 计算列表中元素平均值的不同方法。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。