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

列表的平均值被定义为列表中的元素总和除以列表中的元素数量。

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

  1. 使用 sum()
  2. 使用 reduce()
  3. 使用 mean()

那么,让我们开始吧...

使用 sum()

在第一种方法中,我们使用了 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,该函数以列表作为其参数,并使用 lambda(一种在Python中编写函数的精确方法)在 reduce 中计算平均值。
  3. 然后,我们初始化了要计算其平均值的列表。
  4. 在接下来的步骤中,我们将此列表作为参数传递给我们的函数。
  5. 最后,我们打印出结果值。

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

使用 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. 在第一步中,我们从 statistics 中导入 mean,以便我们可以在程序中使用它来计算元素的平均值。
  2. 现在,我们创建了一个函数 calc_average,该函数以列表作为其参数,并使用 mean() 来计算平均值。
  3. 然后,我们初始化了要计算其平均值的列表。
  4. 在接下来的步骤中,我们将此列表作为参数传递给我们的函数。
  5. 最后,我们打印出结果值。

结论

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

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程