奇怪的索引错误

时间:2015-09-04 09:53:08

标签: python indexing

刚开始使用python进行编程(实际上是编程)并编写了一个持续拒绝正常工作的简短程序。虽然输出看起来很好,但仍然有一些我无法摆脱的错误线。所以我会感激任何帮助/建议。 这是代码:

# takes a list with 5 columns per line as an input
# last name, first name, 3 score - values (exam1, exam2, final)
# prints out a formatted table with first name, last name and a weighted score sum

def parse_line(line_str):
    '''
    :param line_str: expects a line of form last, first, exam 1, exam2, final
    :return: a tuple containing first+last and list of scores
    '''
    field_list = line_str.strip().split(",")
    name_str = field_list[1] + " " + field_list[0]
    score_list = []
    for element in field_list[2:]:
        score_list.append(int(element))
    return name_str, score_list


def weighted_grade(score_list, weights=(0.3, 0.3, 0.4)):
    ''' 
    :param score_list: expects 3 elements in score_list
    :param weights: multiples each element by its weigth
    :return: returns the sum
    '''
    grade_float = \
        (score_list[0] * weights[0]) + \
        (score_list[1] * weights[1]) + \
        (score_list[2] * weights[2])
    return grade_float

grade_file = open("/home/jan/Desktop/Grades.txt", "r")              
print("{:>13s} {:>15s}".format("Name", "Grade"))                # header   of the table
print("-" * 30)
for line_str in grade_file:
    name_str, score_list = parse_line(line_str)                 # passing it the first function, multiple assignment
    grade_float = weighted_grade(score_list)
    print("{:>15s} {:14.2f}".format(name_str, grade_float))     # final table

这是错误消息:

Traceback (most recent call last):
  File "/home/jan/PycharmProjects/introduction/more.py", line 27, in <module>
         Name           Grade
    name_str, score_list = parse_line(line_str)
------------------------------
  File "/home/jan/PycharmProjects/introduction/more.py", line 8, in parse_line
     John Smith          30.00
    name_str = field_list[1] + " " + field_list[0]
 Larry CableGuy          30.00
IndexError: list index out of range
     Try Harder          40.00
   Monty Python         100.00

1 个答案:

答案 0 :(得分:1)

文件中有一行没有逗号。通常会发生这种情况,因为该行完全是空的。因此,str.split()返回一个最多包含1个元素的列表,因此尝试索引元素1(第2个)失败。

略过这些界限:

for line_str in grade_file:
    if ',' not in line:
        continue
    name_str, score_list = parse_line(line_str)                 # passing it the first function, multiple assignment