如何在Python中找到列表的平均值?

[1, 2, 3, 4]  ⟶  2.5

当前回答

假设

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

其他回答

简单的解决方案是avmedii -lib

pip install avemedi_lib

而不是包括在你的剧本中

from avemedi_lib.functions import average, get_median, get_median_custom


test_even_array = [12, 32, 23, 43, 14, 44, 123, 15]
test_odd_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Getting average value of list items
print(average(test_even_array))  # 38.25

# Getting median value for ordered or unordered numbers list
print(get_median(test_even_array))  # 27.5
print(get_median(test_odd_array))  # 27.5

# You can use your own sorted and your count functions
a = sorted(test_even_array)
n = len(a)

print(get_median_custom(a, n))  # 27.5

享受。

xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)

当Python有一个完美的cromulent sum()函数时,为什么要使用reduce()呢?

print sum(l) / float(len(l))

(float()在Python 2中强制Python执行浮点除法是必需的。)

Sum (l) / float(len(l))是正确答案,但为了完整起见,你可以用一个reduce来计算平均值:

>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114

注意,这可能会导致轻微的舍入误差:

>>> sum(l) / float(len(l))
20.111111111111111

如果你想要的不仅仅是平均值(又名平均),你可以看看scipy的统计:

from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))

# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111, 
# variance=572.3611111111111, skewness=1.7791785448425341, 
# kurtosis=1.9422716419666397)