如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)
其他回答
结合上面的几个答案,我提出了以下与reduce一起工作的方法,并且不假设你在reduce函数中有L可用:
from operator import truediv
L = [15, 18, 2, 36, 12, 78, 5, 6, 9]
def sum_and_count(x, y):
try:
return (x[0] + y, x[1] + 1)
except TypeError:
return (x + y, 2)
truediv(*reduce(sum_and_count, L))
# prints
20.11111111111111
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)
你可以为平均值,使用率做一个函数:
average(21,343,2983) # You can pass as many arguments as you want.
代码如下:
def average(*args):
total = 0
for num in args:
total+=num
return total/len(args)
*args允许任意数量的答案。
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
或者像之前写的那样
sum(l)/(len(l)*1.0)
1.0是为了确保你得到一个浮点除法