compute mean in python for a generator

后端 未结 10 2228
遇见更好的自我
遇见更好的自我 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2021-01-01 22:56

    One way would be

    numpy.fromiter(Y, int).mean()
    

    but this actually temporarily stores the numbers.

    0 讨论(0)
提交回复
热议问题