列表索引超出范围

时间:2014-12-18 07:38:07

标签: python mysql list numpy dictionary

所以我通过SQL查询调用一些数据,并且在尝试循环遍历它时,我遇到了列表索引范围的错误,正常化并绘制它。

这是我的SQL:

s1 = db.dict.execute("SELECT sp.wavelength, sp.flux, spt.spectral_type, s.designation, s.shortname, s.names FROM spectra AS sp JOIN sources AS s ON sp.source_id=s.id JOIN spectral_types as spt ON spt.source_id=s.id WHERE sp.instrument_id=6 AND sp.mode_id=2 AND 10<spt.spectral_type<19").fetchall()
s2 = db.dict.execute("SELECT sp.wavelength, sp.flux, spt.spectral_type, s.designation, s.shortname, s.names FROM spectra AS sp JOIN sources AS s ON sp.source_id=s.id JOIN spectral_types as spt ON spt.source_id=s.id WHERE sp.instrument_id=9 AND sp.wavelength_order='n3' AND 10<spt.spectral_type<19").fetchall()
s3 = db.dict.execute("SELECT sp.wavelength, sp.flux, spt.spectral_type, s.designation, s.shortname, s.names FROM spectra AS sp JOIN sources AS s ON sp.source_id=s.id JOIN spectral_types as spt ON spt.source_id=s.id WHERE sp.instrument_id=16 AND 10<spt.spectral_type<19").fetchall()

然后我将它们组合成S:

S = s1+s2+s3

最后,我想循环遍历它们来规范化,修剪和绘制我调用的字典中的所有条目。

for n,i in enumerate(S):
    W,F = S[n]['wavelength'], S[n]['flux'] # here I define wavelength and flux from SQL query "S"
    band = [1.15,1.325] #The range at which I want to normalize, see next line
    S1 = at.norm_spec([W,F], band) # here I normalize W and F and define S1 as the normalized W,F
    W3 = S1[n][0] #here I define a new W and F but from the normalized S1 spectrum file
    F3 = S1[n][1] 
    W2,F2 =[p[np.where(np.logical_and(W3>1.15, W3<1.325))] for p in [W3,F3]] #here I trim the noisy ends of data and narrow to a small range
    z = np.polyfit(W2, F2, 3) #from here on it's just fitting polynomials and plotting
    f = np.poly1d(z)
    yvalue = 6*(max(F2)/9)
    xvalue = 6*(max(W2)/9)
    W_new = np.linspace(W2[0], W2[-1], 5000)
    F_new = f(W_new)
    plt.ylabel('Flux F$_{\lambda}$')
    plt.xlabel('Wavelength ($\mu$m)')
    name= S[n]['designation']
    name2= S[n]['shortname']
    name3= S[n]['names']
    plt.annotate('{0} \n Spectral type: {1}'.format(S[n][('designation' or 'shortname' or 'names')], S[n]['spectral_type']), xy=(xvalue, yvalue), xytext=(xvalue, yvalue), color='black')
    #plt.figure()
    plt.plot(W2,F2, 'k-', W_new, F_new, 'g-')

现在,它经历了第一次迭代,意味着它绘制了S1 [0] [0]和S1 [0] [1],但它打破并说S1 [1] [0]和S1 [1] [1 ]超出范围:     61 print len(S1)     62 #print S1 [n] [&#39;波长&#39;]

--->63         W3 = S1[n][0] #here I define a new W and F but from the normalized S1 spectrum file
64         F3 = S1[n][1]
65         W2,F2 =[p[np.where(np.logical_and(W3>1.15, W3<1.325))] for p in [W3,F3]] #here I trim the noisy ends and narrow to potassium lines

IndexError: list index out of range

我真的不知道我的错误在哪里,任何帮助都将不胜感激!

萨拉

1 个答案:

答案 0 :(得分:0)

如果我理解你的代码,首先你要迭代S的'n'个对象,但是S1是一个全新的对象,其数量不是“n”,而是其他一些(该向量的长度,或者东西)。也许只有W3 = S1[0]才是正确的?虽然,我不知道什么是at.norm_spec以及什么类型的对象是returnig,所以我只是在猜测。

建议:在代码中写入(更多)有意义的变量。 真的,真的难以阅读类似的东西,并且非常,非常很容易在编写这种代码时犯错误。而且它不是pythonic。