简体   繁体   中英

Python list assignment index out of range

I keep getting an IndexError: list assignment index out of range. Here is my code:

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]
mv.append(10.1 - 2.5 * np.log(fv[i]/1220000))
mb.append(11.0 - 2.5 * np.log(fb[i]/339368))

mv[i] wont work because there is no ith index

really I would use a list comprehension

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

and since you are using numpy you can do even better

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM