如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
其他回答
我尝试使用上面的选项,但没有工作。 试试这个:
from statistics import mean
n = [11, 13, 15, 17, 19]
print(n)
print(mean(n))
使用过python 3.5
对于Python 3.8+,使用统计信息。浮点数稳定性的平均值。(快)。
对于Python 3.4+,使用统计信息。平均数值稳定性与浮子。(慢)。
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
对于较旧版本的Python 3,请使用
sum(xs) / len(xs)
对于Python 2,将len转换为浮点数以获得浮点除法:
sum(xs) / float(len(xs))
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
为了使用reduce来获取运行平均值,您需要跟踪到目前为止所看到的元素总数。因为它不是列表中的一个普通元素,所以还必须向reduce传递一个要折叠成的额外参数。
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))
>>> running_average[0]
(181.0, 9)
>>> running_average[0]/running_average[1]
20.111111111111111
numbers = [0,1,2,3]
numbers[0] = input("Please enter a number")
numbers[1] = input("Please enter a second number")
numbers[2] = input("Please enter a third number")
numbers[3] = input("Please enter a fourth number")
print (numbers)
print ("Finding the Avarage")
avarage = int(numbers[0]) + int(numbers[1]) + int(numbers[2]) + int(numbers [3]) / 4
print (avarage)