compute mean in python for a generator

后端 未结 10 2182
遇见更好的自我
遇见更好的自我 2021-01-01 21:58

I\'m doing some statistics work, I have a (large) collection of random numbers to compute the mean of, I\'d like to work with generators, because I just need to compute the

10条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 22:47

    def my_mean(values):
        total = 0
        for n, v in enumerate(values, 1):
            total += v
        return total / n
    
    print my_mean(X)
    print my_mean(Y)
    

    There is statistics.mean() in Python 3.4 but it calls list() on the input:

    def mean(data):
        if iter(data) is data:
            data = list(data)
        n = len(data)
        if n < 1:
            raise StatisticsError('mean requires at least one data point')
        return _sum(data)/n
    

    where _sum() returns an accurate sum (math.fsum()-like function that in addition to float also supports Fraction, Decimal).

提交回复
热议问题