Finding the average of a list

前端 未结 23 1613
抹茶落季
抹茶落季 2020-11-22 11:07

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)
23条回答
  •  忘了有多久
    2020-11-22 11:48

    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
    

    On older versions of Python you can do

    sum(l) / len(l)
    

    On Python 2 you need to convert len to a float to get float division

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

    There is no need to use reduce. It is much slower and was removed in Python 3.

提交回复
热议问题