Iteration over list slices

后端 未结 9 622
名媛妹妹
名媛妹妹 2020-11-30 00:59

I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.

In my mind it is something like:

for list_of_x         


        
9条回答
  •  情深已故
    2020-11-30 02:02

    I am not sure, but it seems you want to do what is called a moving average. numpy provides facilities for this (the convolve function).

    >>> x = numpy.array(range(20))
    >>> x
        array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
           17, 18, 19])    
    >>> n = 2 # moving average window
    >>> numpy.convolve(numpy.ones(n)/n, x)[n-1:-n+1]
    array([  0.5,   1.5,   2.5,   3.5,   4.5,   5.5,   6.5,   7.5,   8.5,
             9.5,  10.5,  11.5,  12.5,  13.5,  14.5,  15.5,  16.5,  17.5,  18.5])
    

    The nice thing is that it accomodates different weighting schemes nicely (just change numpy.ones(n) / n to something else).

    You can find a complete material here: http://www.scipy.org/Cookbook/SignalSmooth

提交回复
热议问题