2016-04-25 80 views
0

当我运行服务器时,它返回一个IndexError:“列表分配索引超出范围”。 由于我的文件rasp.py在第15行,但我没有找到原因。为什么我在运行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] = mystring引发IndexError。使用tab.append(mystring),这会将值附加到字符串的末尾

相关问题