compute mean in python for a generator

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

    Just one simple change to your code would let you use both. Generators were meant to be used interchangeably to lists in a for-loop.

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

提交回复
热议问题