如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
两者都可以在一个整数或至少10个十进制值上给出接近的值。但如果你真的考虑长浮动值,这两者可能是不同的。方法可以根据你想要达到的目标而有所不同。
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> print reduce(lambda x, y: x + y, l) / len(l)
20
>>> sum(l)/len(l)
20
浮动值
>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111
@Andrew Clark的说法是正确的。
其他回答
当Python有一个完美的cromulent sum()函数时,为什么要使用reduce()呢?
print sum(l) / float(len(l))
(float()在Python 2中强制Python执行浮点除法是必需的。)
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
或者像之前写的那样
sum(l)/(len(l)*1.0)
1.0是为了确保你得到一个浮点除法
假设
x = [
[-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
[-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
[-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]
你可以注意到x的维数是3*10如果你需要得到每一行的平均值,你可以输入这个
theMean = np.mean(x1,axis=1)
不要忘记将numpy导入为np
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)
我想补充另一种方法
import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)