I have a .csv file with names and scores. Here are the files contents (The name and score are in separate columns):
Bob 1
Dave 6
Linda 9.76
Andy 90
hilary 87
mathew 6.4576589
The program should display the scores from highest to lowest. Like this:
Bob 1
Dave 6
mathew 6.4576589
Linda 9.76
hilary 89
Andy 90
I have been trying this for ages. Here is my code below:
import csv
import operator
out_file = open('class1_scores_max.csv','r')
scores1 = csv.reader(out_file,delimiter=',')
sort = sorted(scores1,key = lambda x: float(x[1]))
for eachline in sort:
final = eachline[0]," ",eachline[1]
print (''.join(final))
This work perfectly in a separate python file but in my main Controlled Assessment in school it comes up with the error:
IndexError: list index out of range
In my main code at school it is part of a definition (sub-routine). Can anyone help?
From what you've provided, you're getting an IndexError
at either of these two lines:
sort = sorted(scores1,key = lambda x: float(x[1]))
or
final = eachline[0]," ",eachline[1]
I suspect that you're IndexError
is at the first line, because getting an IndexError
at the second line seems to imply that it would've occured at the first as well.
You can fix this by making sure there's two elements in each line before sorting and printing them.
sort = sorted([x for x in scores1 if len(x) == 2], key = lambda x: float(x[1]))
This is also a great time to learn the basics of debugging. Suppose you didn't have help from the internet and had to debug this problem on your own. Adding a few print statements is one of the quickest and simplest ways to debug code. For example,
import csv
import operator
out_file = open('class1_scores_max.csv','r')
scores1 = csv.reader(out_file,delimiter=',')
for score in scores1:
print score
sort = sorted(scores1,key = lambda x: float(x[1]))
for eachline in sort:
final = eachline[0]," ",eachline[1]
print (''.join(final))
Notice where I inserted the following lines:
for score in scores1:
print score
This will allow you to see if there's anything in scores1
that might lead to an IndexError
later on when you try to access the first and second elements of a an element in scores1
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments