compute mean in python for a generator

后端 未结 10 2235
遇见更好的自我
遇见更好的自我 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条回答
  •  旧时难觅i
    2021-01-01 22:51

    Try:

    import itertools
    
    def mean(i):
        (i1, i2) = itertools.tee(i, 2)
        return sum(i1) / sum(1 for _ in i2)
    
    print mean([1,2,3,4,5])
    

    tee will duplicate your iterator for any iterable i (e.g. a generator, a list, etc.), allowing you to use one duplicate for summing and the other for counting.

    (Note that 'tee' will still use intermediate storage).

提交回复
热议问题