compute mean in python for a generator

后端 未结 10 2230
遇见更好的自我
遇见更好的自我 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:55

    def my_mean(values):
        n = 0
        sum = 0
        for v in values:
            sum += v
            n += 1
        return sum/n
    

    The above is very similar to your code, except by using for to iterate values you are good no matter if you get a list or an iterator. The python sum method is however very optimized, so unless the list is really, really long, you might be more happy temporarily storing the data.

    (Also notice that since you are using python3, you don't need float(sum)/n)

提交回复
热议问题