Finding the average of a list

前端 未结 23 1840
抹茶落季
抹茶落季 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:56

    Both can give you close to similar values on an integer or at least 10 decimal values. But if you are really considering long floating values both can be different. Approach can vary on what you want to achieve.

    >>> 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
    

    Floating values

    >>> print reduce(lambda x, y: x + y, l) / float(len(l))
    20.1111111111
    >>> print sum(l)/float(len(l))
    20.1111111111
    

    @Andrew Clark was correct on his statement.

提交回复
热议问题