Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

How do I sort my File (highscores) with python?

I'm currently working on a dice game for my computer science coursework. I'm on the last bit of it which requires me to sort my highscores into a text file. This is what I have so far

player1=input("input") ##Temporary inputs (these values are got from the actual code)
player1score=int(input("input"))


highscore = open("Scores.txt", "r")
whowon=("{0}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("
")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()
highscores.sort()
highscores.reverse()


top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]

top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))

highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()


Basically, in the document, it sorts them into order but it disregards the amount of place holders it has. For example:

8
7
6943734
5

It would only sort it depending on the first place holder. And i dont know how to fix it. Obviously 6943734 should be at the top.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace:

highscores.sort()
highscores.reverse()

with

highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)

The first line removes newline characters from your strings, so they can be converted to integers using int() function, the second - sorts in descending order according to int value. BTW, this part:

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))

can be shortened to:

top = '
'.join(highscores[0:5])

(here you need to add newlines back before writing your highscores to a file).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...