I've been trying to figure out how to sort results in a text file in order of test scores for a small task I'm doing using the lambda sort function. I'm unsure if this is the best way to do this or not but it was recommended to me by a friend.
The results are entered into the text file like so:
text_file = open("Results.txt", "a")
text_file.write("\n")
text_file.write(str(score))
text_file.write(" ")
text_file.write(userName)
text_file.write(" ")
text_file.write(userClass)
text_file.close()
My current sorting system looks like this:
with open("Results.txt") as inf:
data = []
for line in inf:
line = line.split()
if len(line)==4:
data.append(line)
a = sorted(a, key=lambda x: x.modified, reverse=True)
And the text file looks like this:
5 Test b
4 Test b
6 Test c
7 Test a
(score userName userClass)
I would like to sort the results in descending order by score and I'm not sure this is the correct way to go about it.
Thanks in advance.
x.modified?if len(line)==4:when you only have 3 elements in each line (score, userName and userClass)?asupposed to be in your code? And dtw, you have to add a level of indentation afterwith open...x.modifiedhas no meaning. Yourdatalist consists of lists with 3 elements. So you should usekey=lambda x: x[0]instead.