compute mean in python for a generator

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

    Your approach is a good one, but you should instead use the for x in y idiom instead of repeatedly calling next until you get a StopIteration. This works for both lists and generators:

    def my_mean(values):
        n = 0
        Sum = 0.0
    
        for value in values:
            Sum += value
            n += 1
        return float(Sum)/n
    

提交回复
热议问题