Python列表分配索引超出范围

时间:2013-06-04 19:18:09

标签: python indexing range out

我不断收到IndexError:列表分配索引超出范围。 这是我的代码:

import numpy as np
import asciidata

fv = [] 
fb = []
data = asciidata.open('Flux.txt')
for i in data[1]:
    fv.append(float(i))
for i in data[2]:
    fb.append(float(i))

mv = []
mb = []
for i in range (0,25):
    mv[i] = 10.1 - 2.5 * np.log(fv[i]/1220000)
    mb[i] = 11.0 - 2.5 * np.log(fb[i]/339368)
    print i, mv[i], mb[i]

1 个答案:

答案 0 :(得分:6)

mv.append(10.1 - 2.5 * np.log(fv[i]/1220000))
mb.append(11.0 - 2.5 * np.log(fb[i]/339368))

mv [i]不会工作,因为没有第i个索引

我真的会使用列表理解

mv = [10.1 - 2.5 * np.log(val/1220000) for val in fv]

因为你正在使用numpy,你可以做得更好

fv = np.array(fv)
mv = 10 - np.log(fv/1220000)*2.5