将文本文件中的分数从最高到最低排序,并使错误元组索引超出范围

时间:2015-08-30 14:29:17

标签: python sorting

我有一个文本文件,学生分数来自考试,我需要找到每个学生的最高分,然后打印每个学生的最高分,按从高到低的顺序。

我的代码低于下面但是我一直让元组索引超出范围。

classChoice = str(input('What class scores would you like to view; rat, wolf or polar bear '))
fileName = 'results/' + classChoice + ".txt"
# init a list where you store the results
results = []
# open the file with results in a "read" mode
with open(fileName, "r") as fileinput:
# for each line in file with results, do following
    for line in fileinput:
    # remove whitespaces at the end of the line and split the line by ":"
    items = line.strip().split(":")
    # store the result as a list of tuples
    results.append(tuple(items))

# first it sorts all the tuples in `results` tuple by the second item (score)
# for each result record in sorted results list do the following
for result_item in sorted(results, key=lambda x: x[1], reverse=True):
# print the result in the format of the scores in your file 
    print ("{}:{}".format(result_item[0], result_item[1]))

2 个答案:

答案 0 :(得分:0)

您至少有一个没有2个值的元组。这意味着您有空行或其中没有:个字符的行:

>>> 'student\n'.strip().split(':')
['student']
>>> len('student\n'.strip().split(':'))
1
>>> '\n'.strip().split(':')
['']
>>> '\n'.strip().split(':')[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

通过测试:字符或生成的items列表的长度来防范这种情况。

:的测试非常简单:

for line in fileinput:
    if not ':' in line:
        # not a valid line, empty or not a key-value pair
        continue
    items = line.strip().split(":")
    # store the result as a list of tuples
    results.append(tuple(items))

答案 1 :(得分:-1)

我想也许那是因为你忘记了从文件中删除阅读的行。 尝试选择第9-12行。

那会对你有所帮助 Short Description of the Scoping Rules?