繁体   English   中英

如何使用 python 对我的文件(高分)进行排序?

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

我目前正在为我的计算机科学课程制作一个骰子游戏。 我在它的最后一点,这需要我将我的高分分类到一个文本文件中。 这是我到目前为止

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("\n")
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()


基本上,在文档中,它按顺序对它们进行排序,但忽略了它拥有的占位符数量。 例如:

8
7
6943734
5

它只会根据第一个占位符对其进行排序。 我不知道如何解决它。 显然 6943734 应该在顶部。

谢谢。

代替:

highscores.sort()
highscores.reverse()

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

第一行从字符串中删除换行符,因此可以使用int()函数将它们转换为整数,第二行根据 int 值按降序排序。 顺便说一句,这部分:

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))

可以缩短为:

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

(在这里,您需要在将高分写入文件之前添加换行符)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM