此代码我总是收到此错误:
Traceback (most recent call last):
File "E:/ankosh/trial13.py", line 14, in <module>
if grades_mix[index_no]=="HM1":
IndexError: list index out of range)
我真的很感激帮助。
`file_pointer=open("C:/python27/Doc/student_grades.txt", "r")
read_grades=file_pointer.readline()
my_list=[]
while 0==0:
grades_mix=read_grades.split()
name_str=grades_mix[0]
contained_list=[name_str,0,0,0,0,0.0]
index_no=1
count_num=0
sum_float=0.0
avg_float=0.0
while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[1]=grade_num
elif grades_mix[index_no]=="HM2":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[2]=grade_num
elif grades_mix[index_no]=="HM3":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[3]=grade_num
elif grades_mix[index_no]=="HM4":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[4]=grade_num
index_no+=1
if count_num>0:
avg_float=sum_float/count_num
contained_list[5]=avg_float
index_num=0
while index_num<len(my_list):
if my_list[0]>name_str:
break
index_no+=1
my_list.insert(index_num, contained_list)
read_grades=file_pointer.readline()
file_pointer.close()
print format ("Name","<10")+" | "+format("HM1"," >5")+" | "+format("HM2"," >5")+" | "+format("HM3"," >5")+" | "+format("HM4"," >5")+" | "+format("avg_float"," <10")+" | "
for index_no in range(0, len(my_list)):
print format(my_list[index_num][0], "<10") + " | " + \
format(my_list[index_num][1], " >5") + " | " + \
format(my_list[index_num][2], " >5") + " | " + \
format(my_list[index_num][3], " >5") + " | " + \
format(my_list[index_num][4], " >5") + " | " + \
format(my_list[index_num][5], " >10.2f") + " | "
答案 0 :(得分:3)
您的缩写形式为:
while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
没有break语句可以离开循环(哪个while True
怎么样?)。迟早你会超出范围。
答案 1 :(得分:1)
错误消息
IndexError: list index out of range
表示您正在使用数组中不存在的索引。尝试通过打印出长度来检查数组的大小
print“数组的长度grade_mix =”,len(grades_mix)
如果数组的长度小于或等于1,则在调用时第一步会出现错误
grades_mix[index_no]
与
index_no=1
您的文件可能包含空行或带有单个单词的行,您需要在脚本中处理它。