0

I have a set of data points for which I have made a program that will look into the data set, from that set take every n points, and sum it, and put it in a new list. And with that I can make a simple bar plots.

Now I'd like to calculate a discrete mean for my new list.

The formula I'm using is this: t_av=(1/nsmp) Sum[N_i*t_i,{i,n_l,n_u}]
Basically I have nsmp bins that have N_i number in them, t_i is a time of a bin, and n_l is the first bin, and n_u is the last bin.

So if my list is this: [373, 156, 73, 27, 16],
I have 5 bins, and I have: t_av=1/5 (373*1+156*2+73*3+27*4+16*5)=218.4

Now I have run into a problem. I tried with this:

for i in range(0,len(L)):
    sr_vr = L[i]*i

tsr=sr_vr/nsmp

Where nsmp is the number of bins I can set, and I have L calculated. Since range will go from 0,1,2,3,4 I won't get the correct answer, because my first bin is calculated by 0. If I say range(1,len(L)+1) I'll get IndexError: list index out of range, since that will mess up the L[i]*i part since he will still multiply second (1) element of the list with 1, and then he'll be one entry short for the last part.

How do I correct this?

4

1 回答 1

1

您可以使用L[i]*(i+1)(假设您坚持使用从零开始的索引)。

但是,您也可以使用一起enumerate()循环索引和值,甚至可以提供1作为第二个参数,以便索引从.10

这是我将如何写这个:

tsr = sum(x * i for i, x in enumerate(L, 1)) / len(L)

请注意,如果您使用的是 Python 2.x 并且L完全包含整数,则这将执行整数除法。要获得浮点数,只需将其中一个参数转换为浮点数(例如float(len(L)))。您也可以使用from __future__ import division.

于 2013-05-16T23:21:29.893 回答