2016-04-25 7 views
0

私が実行すると、IndexError: "リスト割り当てインデックスが範囲外です"が返されます。 行15の私のファイルrasp.pyのために、私は理由を見つけませんでした。Djangoプロジェクトを実行するときにIndexErrorが発生するのはなぜですか?

rasp.py

#!/usr/bin/env python 
def foo () : 
    tab= [ ] 
    i = 0 
    for i in range(12): 
     tfile = open("/sys/bus/w1/devices/28-000007101990/w1_slave") 
     text = tfile.read() 
     tfile.close() 
     secondline = text.split("\n")[1] 
     temp = secondline.split(" ")[9] 
     temperature = float(temp[2:]) 
     temperature = temperature/1000 
     mystr = str(temperature) 
     mystring = mystr.replace(",",".") 
     tab [i] = mystring 
    return tab 

答えて

0

リストに存在しないインデックスにアクセスしようとしているため、IndexErrorが表示されています。

代わりの指標でそれにアクセスするには、メソッドappend使用できます

#!/usr/bin/env python 
def foo () : 
    tab= [] 
    for i in range(12): 
     tfile = open("/sys/bus/w1/devices/28-000007101990/w1_slave") 
     text = tfile.read() 
     tfile.close() 
     secondline = text.split("\n")[1] 
     temp = secondline.split(" ")[9] 
     temperature = float(temp[2:]) 
     temperature = temperature/1000 
     mystr = str(temperature) 
     mystring = mystr.replace(",",".") 
     tab.append(mystring) 
    return tab 
0

tabはそれがtab[i] = mystringIndexErrorを上げる理由である、有効なインデックスを持っていないことを意味空のリスト、です。 tab.append(mystring)を使用して、文字列の末尾に値を追加します。

関連する問題