查找列表的平均值 [英] Finding the average of a list
本文介绍了查找列表的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须在Python中找到列表的平均值.到目前为止,这是我的代码
I have to find the average of a list in Python. This is my code so far
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
我已经知道了,所以它可以将列表中的值相加,但是我不知道如何将其划分为它们?
I've got it so it adds together the values in the list, but I don't know how to make it divide into them?
推荐答案
在Python 3.4+上,您可以使用 statistics.mean()
On Python 3.4+ you can use statistics.mean()
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(l) # 20.11111111111111
在旧版本的Python上,您可以做到
On older versions of Python you can do
sum(l) / len(l)
在Python 2上,您需要将len
转换为浮点数以进行浮点除法
On Python 2 you need to convert len
to a float to get float division
sum(l) / float(len(l))
无需使用reduce
.它要慢得多,并且在Python 3中已已删除.
There is no need to use reduce
. It is much slower and was removed in Python 3.
这篇关于查找列表的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文