在Python中查找列表的平均值
先决条件:sum()函数、len()函数、round()函数、reduce()、lambda 和 mean()。
给定一个数字列表,任务是找到该列表的平均值。平均值是元素的总和除以元素的数量。
例子:
Input : [4, 5, 1, 2, 9, 7, 10, 8]
Output : Average of the list = 5.75
Explanation:
Sum of the elements is 4+5+1+2+9+7+10+8 = 46
and total number of elements is 8.
So average is 46 / 8 = 5.75
Input : [15, 9, 55, 41, 35, 20, 62, 49]
Output : Average of the list = 35.75
Explanation:
Sum of the elements is 15+9+55+41+35+20+62+49 = 286
and total number of elements is 8.
So average is 46 / 8 = 35.75
使用总和()
在Python中,我们可以通过简单地使用sum()和len()函数来找到列表的平均值。
- sum() :使用 sum()函数我们可以得到列表的总和。
- len() : len()函数用于获取列表中元素的长度或数量。
# Python program to get average of a list
def Average(lst):
return sum(lst) / len(lst)
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
输出:
Average of the list = 35.75
使用 reduce() 和 lambda
我们可以使用 reduce() 来减少循环,并且通过使用 lambda函数可以计算列表的总和。如上所述,我们使用 len() 来计算长度。
# Python program to get average of a list
# Using reduce() and lambda
# importing reduce()
from functools import reduce
def Average(lst):
return reduce(lambda a, b: a + b, lst) / len(lst)
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
输出:
Average of the list = 35.75
使用均值()
内置函数mean() 可用于计算列表的均值(平均值)。
# Python program to get average of a list
# Using mean()
# importing mean()
from statistics import mean
def Average(lst):
return mean(lst)
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
输出:
Average of the list = 35.75