我使用了https://stackoverflow.com/a/53299137/11001876中的代码,到目前为止,它仍然有效,但是我不确定如何将高分限制为仅5分,而高分文本文件中的得分最高。我已经编辑了链接中的代码以适合我的程序:
# Winning Code
elif U1Score > U2Score:
print(username1, "Won")
highscores = open("highscores.txt", "r")
highscores.close()
with open('highscores.txt', 'w') as f:
for username1, U1Score in scores:
f.write('Username: {0}, Score: {1}\n'.format(username1, U1Score))
highscores.close()
highscores = open("highscores.txt", "r")
print(highscores.read())
highscores.close()
else:
print(username2, "Won")
highscores = open("highscores.txt", "r")
highscores.close()
with open('highscores.txt', 'w') as f:
for username2, U2Score in scores:
f.write('Username: {0}, Score: {1}\n'.format(username2, U2Score))
highscores.close()
highscores = open("highscores.txt", "r")
print(highscores.read())
highscores.close()
但是,我仍然不确定如何将分数限制为5个不同的分数,以及如何从最高到最低排序。谢谢,我是新来的:)
最佳答案
一个简单的解决方案是代替打印file.read()逐行读取文件(因为您使用的分隔符为line),然后仅打印5行。
可能是这样的:
f = open("highscores.txt", "r")
highscores_lines = f.read()
for line in highscores_line[:5]:
print(line)
而且,如果要按降序排序和打印,则可以按每行中的数字使用某种排序算法,并在打印前对行进行排序。
排序参考-https://www.programiz.com/python-programming/methods/list/sort#targetText=The%20sort()%20method%20sorts,()%20for%20the%20same%20purpose。
关于python - 如何使我的高分文本文件只有5个高分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58199045/